Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange error while using word variation C++ not operator

Tags:

c++

boolean

I have the following check in my C++ code:

if (not obj.someBoolean) {
      // some code
} else {
      // some other code
}   

A print statement or gdb confirms that obj.someBoolean (a bool variable) is false.
Yet the control goes to the else block while using not operator.

Interestingly, the ! variety of the operator works correctly when used in the above scenario (goes into the if block).

Is this an issue with the way I am using not?

Update (some more details on the scenario):

Throughout the code I have used not in many places. But this is one scenario where this issue comes up (consistently).

Even the following code works (goes to if block):

bool temp = not obj.someBoolean;
if (temp) {
      // some code
} else {
      // some other code
}     

This is more like a single random point where it is happening.
I was curious as to why this behavior is caused.

like image 959
eternalthinker Avatar asked May 24 '26 08:05

eternalthinker


2 Answers

I use not, and and or almost exclusively in C++ (I find them more readable and less error prone than their sigils counterparts). They are strictly equivalent.

§2.6 Alternative tokens [lex.digraph]

1/ Alternative token representations are provided for some operators and punctuators.

2/ In all respects of the language, each alternative token behaves the same, respectively, as its primary token, except for its spelling. The set of alternative tokens is defined in Table 2.

Look elsewhere.

like image 134
Matthieu M. Avatar answered May 25 '26 22:05

Matthieu M.


I don't see what's wrong with your code. Try this:

#include <iostream>

int main()
{
  if(not false) std::cout<< "true!"; 
}

If it prints "true!", the problem is somewhere else.

like image 37
nurettin Avatar answered May 25 '26 21:05

nurettin