Ternary Operator and Boolean


I have asked a question on stackoverflow:

1
2
3
4
5
inline int 
test(int n, int tag, int flag) {
  if (0 == flag) return ((n & tag) == tag);
  return ((n & tag) != tag);
}
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 ..)

1
2
3
4
inline int 
test(int n, int tag, int flag) {
  return (0 == flag) ? ((n & tag) == tag) : ((n & tag) != tag);
}
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’.

1
2
3
4
5
inline int 
test(int n, int tag, int flag) {
  bool b_flag = flag;
  return !b_flag * ((n & tag) == tag) + b_flag * ((n & tag) != tag);
}
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.

1
2
3
4
if (x) 
  return y;
else
  return !y;
if (x) 
  return y;
else
  return !y;

can be converted to

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

So, the answer is:

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

Or,

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

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
322 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

Leave a Reply