This line of code outputs 0
:
std::cout << !+2;
I think it should be 35
, since '!' has an ASCII code of 33
and adding 2
to it equals 35
.
Why is it like that?
This line of code outputs 0
:
std::cout << !+2;
I think it should be 35
, since '!' has an ASCII code of 33
and adding 2
to it equals 35
.
Why is it like that?
Let's quickly analyze what your code !+2
does. The bare exclamation mark is the logical not operator which negates the truth value of its operand. Integers, such as +2
can be converted to boolean, where 0
means false
and every non-zero integer true
. That means that !+2
is converted to !true
. The negation of true
is obviously false
, so !+2
is converted to false
. When you pipe this boolean into std::cout
is is converted to integer again, i.e. true
turns into 1
and false
turns into 0
. That is why you std::cout << !+2;
prints 0
.
What you wanted to do instead (add 2 to the ASCII code of !) can be achieved as well. Therefore you have to tell the compiler that you want the character !
by enclosing it in single quotes. Then the code std::cout << ('!' + 2);
will print 35, as expected. I added some extra parentheses to not rely purely on operator precedence.
#include <iostream>
int main() {
std::cout << ('!' + 2) << '\n';
}
Output:
35
If you want to get the ASCII value of exclamation mark, you need to surround it with single quotes like following.
std::cout << '!' + 0;
What you did is negating a value (this value can be either True or False). Making the value (here integer) positive or negative does not matter (here you explicitly specify 2 as positive), because everything other than zero means True. So, if you do the same thing for zero like following, you would get 1 as output.
std::cout << !+0;