Lately I've been noticing the style of some programmers who write "if" statements backwards. That is, in the test they put the constant value first and then the variable that they are testing second. So for example they write:
bar = foo();
if (MY_CONSTANT == bar) {
/* then do something */
}
To me, this makes code somewhat difficult to read. Since we are really talking about testing the value of the variable "bar" and not all variables that are equal to "MY_CONSTANT", I always put the variable first. Its sort of a unspoken grammar.
Anyhow, I see that some programmers ALWAYS do this in the opposite order. Further, I've only noticed this in the past few years. I've been programming in C for over 25 years and I've not seen this until, say, about the last 4 years or so. So my question is:
Is there a reason people are doing this and if so what is it? Is this a common standard in some languages, or projects, or is it taught in some universities? or is that just a few people trying to be different?
There are three forms of IF statements: IF-THEN , IF-THEN-ELSE , and IF-THEN-ELSIF . The simplest form of IF statement associates a Boolean expression with a sequence of statements enclosed by the keywords THEN and END IF .
The Ternary Operator One of my favourite alternatives to if...else is the ternary operator. Here expressionIfTrue will be evaluated if condition evaluates to true ; otherwise expressionIfFalse will be evaluated. The beauty of ternary operators is they can be used on the right-hand side of an assignment.
Nope. In fact, it'll actually speed it up in most cases (because it's allowed to skip over blocks of code).
This is called "Yoda-Style" (or "Yoda conditions" or "Yoda notation") and should prevent you from accidentally writing
if (bar = MY_CONSTANT) {
/* then do something */
}
since
if (MY_CONSTANT = bar) {
/* then do something */
}
would trigger a compiler error.
The name is derived from the uncommon twisted sentence construction the Star Wars character Yoda is also using.
In my opinion using "Yoda-Style" makes understanding of code harder because it is against the normal sentence construction rules. Also code quality checker (or as mentioned in the comments maybe even the compiler itself) should complain about such assignments anyway, so that (imho) there is no good reason to obfuscate your code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With