Algorithms, Blockchain and Cloud

Ternary Operator and Boolean


I have asked a question on stackoverflow:

inline int 
test(int n, int tag, int flag) {
  if (0 == flag) return ((n & tag) == tag);
  return ((n & tag) != tag);
}

How to shorten this/optimise this without using ‘if else’ statement. One solution is to use Ternary Operator, which is supported in many programming languages (especially C-like, C/C++, C#, Java, Javascript ..)

inline int 
test(int n, int tag, int flag) {
  return (0 == flag) ? ((n & tag) == tag) : ((n & tag) != tag);
}

However, this is not what I expect. Many others do not support Ternary Operator, for example, Delphi/Pascal. Some might argue that Ternary Operator is actually a kind of ‘if .. else’.

inline int 
test(int n, int tag, int flag) {
  bool b_flag = flag;
  return !b_flag * ((n & tag) == tag) + b_flag * ((n & tag) != tag);
}

Why bother eliminating this? If this function is invoked a million times, then the efficiency does matter. Removing condition branch check improve the code efficiency. The code execution benefits from prefetching (cache). However, pre-optimisation is the root of evil, make sure you profile the application and find out the performance bottleneck.

My friend told me there is another simplified solution.

if (x) 
  return y;
else
  return !y;

can be converted to

return !(x^y);  // ^ is exclusive or

So, the answer is:

return !(flag ^ ((n & tag) == tag));

Or,

return (flag ^ ((n & tag) != tag));

–EOF (The Ultimate Computing & Technology Blog) —

305 words
Last Post: How to Get the list of emails from the WordPress Comments?
Next Post: Removing Bits - Two Methods

The Permanent URL is: Ternary Operator and Boolean (AMP Version)

Exit mobile version