Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coding style of "if" statements [duplicate]

Tags:

c

coding-style

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?

like image 888
msundius Avatar asked Apr 19 '16 15:04

msundius


People also ask

What are the three variants of IF statement?

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 .

Is a replacement of series of if-else statement?

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.

DO IF statements make code slower?

Nope. In fact, it'll actually speed it up in most cases (because it's allowed to skip over blocks of code).


1 Answers

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.

like image 150
vlad_tepesch Avatar answered Oct 03 '22 16:10

vlad_tepesch