A classic way to guard against accidental use of assignment in logic statements is to write it "backwards", i.e.:
if (2 == x) {...}
Since (2 = x) won't compile, while (x = 2) will not only compile but might appear to work for a very long time.A classic way to guard against accidental use of assignment in logic statements is to write it "backwards", i.e.:
if (2 == x) {...}
Since (2 = x) won't compile, while (x = 2) will not only compile but might appear to work for a very long time.And the errors result from typing "=" when you needed "==" has nothing to do with mathematics. It is a language ergonomics issue resulting from two operators being legal in the same context and one being similar to (a prefix of) the other.
The equals sign has been used for hundreds of years in mathematics and it's completely unnecessary to change this meaning.
Variable on left is conventional, it's how people sound it out in their head, so it's just easier to process mentally when the expression becomes more complex.
Yoda syntax catches that single error at the expense of making all equality expressions harder to write, read and maintain.
And, besides, if you're going to use Yoda syntax, you're going to want your linter to enforce it... at which point you may as well turn on -Wall anyway.
ben@burnination ~ $ cat test.c
int main() {
int a = 3;
int b = 2;
if (a=b) {
return 1;
} else {
return 0;
}
}
ben@burnination ~ $ clang -Wall test.c
test.c:4:10: warning: using the result of an assignment as a condition without parentheses [-Wparentheses]
if (a=b) {
~^~
test.c:4:10: note: place parentheses around the assignment to silence this warning
if (a=b) {
^
( )
test.c:4:10: note: use '==' to turn this assignment into an equality comparison
if (a=b) {
^
==
1 warning generated.