1
unsigned int test=1;

if(test) 
{
   //do something
}
if(test==1)
{
   //do something
}

These two if-conditions are equivalent, right? I am currently debugging a bigger program, where this makes a difference. But it should have no side effects, right?

Simon
  • 325
  • 1
  • 6
  • 7
    No, these are not equivalent. `if(test)` and `if(test != 0)` would be equivalent. – Yksisarvinen Mar 30 '23 at 15:02
  • 1
    They are equivalent with the provided initialization only. But if `test` is initialized to any other (than `1`) non-zero value they won't be. – Eugene Sh. Mar 30 '23 at 15:03
  • Why would they be not equivalent then? – Simon Mar 30 '23 at 15:06
  • @Simon Because `test != 0` is not equivalent to `test == 1`. There are over four billion cases where the first is true but the second isn't. – molbdnilo Mar 30 '23 at 15:07
  • Because if `test` is `2`, then what will happen? – Eugene Sh. Mar 30 '23 at 15:07
  • What do you mean? `if(test)` will run if `test` is `1`, `5`, `42` or `4294967295`. `if(test == 1)` will only run if `test` is `1`. – Yksisarvinen Mar 30 '23 at 15:08
  • Of course. test is initialized with either zero or one. If zero, the if-statement should NOT be excecuted and if one it should. That said, both variants in my question achieve this, right? – Simon Mar 30 '23 at 15:09
  • 3
    Yes, if `test` is only ever `0` or `1`, then these two `if` statements will have the same behaviour. But if you want to limit yourself to two values, I suggested using the right type for that - `bool`. – Yksisarvinen Mar 30 '23 at 15:11

0 Answers0