Hacker News new | past | comments | ask | show | jobs | submit login

The C designers wanted to be able to write stuff like `while ((ch = getchar()) != EOF) { ... }`, so assignment needed to be an expression. Secondly, C had no boolean type, and instead integers were used for boolean values (zero is false, nonzero is true). The combination of these two facts entails that an integer assignment is also a valid boolean expression.

To prevent accidental or malicious use of the assignment operator in place of the equals operator in a language, you either have to have a real boolean type, and no implicit conversion of other types to boolean, or make assignments not be an expression, or disallow assignment expressions in boolean contexts.

Making both operators the same symbol is not a good solution IMO, because it makes it harder to distinguish which is which in arbitrary contexts. E.g. in `a = b = c`, presumably the first is an assignment and the second a comparison? Or maybe not? It would just be confusing. Not sure which languages you are referring to that do this.




A common idiom to defang this was the "Yoda assignment":

  if (0 == do_something(foo)) { ... }
If one accidentally omits one equals-sign, it makes the compiler barf instead of becoming a silent-but-deadly kind of bug (whether intentional or not).

In Go, an assignment is not an expression, so the whole thing becomes illegal. I found this approach a bit offensive at first, but I got used to it rather quickly.


> or make assignments not be an expression,

Or just reverse the expression:

    0 == curent->uid
So that the bug case is an error:

    0 = current->uid


Yes, that is well known, but it doesn’t prevent the issue in TFA.


How does it not? Applied literally to the article, it would have turned this backdoor into a compile time error.


Because you can’t trust the person backdooring your code to help you out by writing in this style.


Yes, they could literally violate the coding style, but presumably, that would draw more attention to what they've done, not less.




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

Search: