Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

What did you change it to?


This is pure speculation, but they may have changed it to foo==false. In C a boolean is just a byte which conventionally has the values 0 or 1, but an attacker which controls a boolean can give it the value of 2, and 2!=true and 2!=false. This has lead to real exploits: https://windows-internals.com/exploiting-a-simple-vulnerabil...

When writing C or C++, never compare against true.


I'm not sure that's right.

Too lazy to look it up right now, but my recollection is that in C, 0 is False and anything else is True.


Nonzero values are truthy. You can use them bare in predicates. But they are not "== true."


if 47 evaluates the true branch. So in that sense you are correct, however standard C99 (the above mentioned bug uses win32's TRUE which is defined the same way) does #define true 1 therefore 47==true is false, even if 47 is true when evaluated.

int a = 47;

if a is true

if a == true is false

if a == false is false

int b;

b = a == true; b = 0

b = a != true; b = 1

b = a == false; b = 0

b = a != false; b = 1


I'd guess if(!foo). It makes sense in some languages where the value can only be either true or false. It will lead to nasty bugs if the value can be null, or the language has truthy-falsy values and the condition accepts non bool values


You and muricula's sibling comment is the reason I asked :) Occasionally it is hard to spot the "!" between "if" and "(", and having to figure out if it is an omission or it was deliberate. I was wondering if spelling it out as "foo == false" is worthwhile.


At one job I had, our programming standards dictated that we would have to write "if (false == foo)" to account for the case where someone accidentally types = instead of ==


Commonly called "Yoda conditions":

https://en.wikipedia.org/wiki/Yoda_conditions


That's not rare, anyway... unless the linter can flag == <bool>, and suggest fixes.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: