0

Basically, how does an if-statement analize whether an integer is true or false? These two simple lines print out "Hello", with a positive integer 764:

int a=764;
if(a){ cout<<"Hello"; }else{ cout<<"Bye"; } //Hello

If i change the integer from positive to negative (-231) it prints out "Hello" as well:

int a=-231;
if(a){ cout<<"Hello"; }else{ cout<<"Bye"; } //Hello

But if i set a to be 0, it gets false

int a=0;
if(a){ cout<<"Hello"; }else{ cout<<"Bye"; } //Bye

It goes true with the range of a long int, from -2147483647 to 2147483647 with only one exception: 0. How does that happen? And what is that if actually doing to determine so?

  • To looks like the conversion from int to Boolean happens based on the value of integer. If it is 0 it is returns false and for anything other than 0 it returns true. – Chetan Apr 25 '19 at 01:41
  • You can check it out here: https://en.cppreference.com/w/cpp/language/implicit_conversion#Boolean_conversions – Fabio says Reinstate Monica Apr 25 '19 at 01:49

1 Answers1

1

This is the expected behavior by design. An if (condition) { ... } else { ... } statement in C/C++ evaluates a boolean expression that will ultimately be either true (the if block executes) or false (the else block executes). When you pass an integer as a condition, it must necessarily be reduced to either true or false, and the compiler actually interprets this as if (integer != 0). This will be the same for whatever integer type, signed or unsigned.

This is a very common idiom in C/C++, although one may argue that it is not the most legible of notations, and you should always make it explicit that you intend to verify whether the integer is 0 or not by using if (integer != 0).

John Kugelman
  • 349,597
  • 67
  • 533
  • 578