-2

In C, for the if statement, sometime we can see that the test 'value is placed before the variable to test, this probably brings some optimization (GCC compiler), but which one ? (but this decreases the readability I think).

Example:

if ( 10 == val) {}

Thanks,

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
  • 3
    Not using this you shall, young padawan. Your compiler to trust to warn you should. – too honest for this site Jan 27 '16 at 14:21
  • Apart from definitively flagging accidental assignment, (as posted by iharob), it makes debugging easier, especially of another's code), by, usually, moving the conditional operator nearer to the start of the line, especially when testing the return value of function calls with many parameters. Who wants to scroll all the way to the RHS of a line to find out what the condition is? – Martin James Jan 27 '16 at 14:31
  • 1
    Example; 'if(WAIT_TIMEOUT==WaitForMultipleObjectsEx(drone,drone,gunge,buzz,thingy,stuff..................................................................) CreateThread(gunge, gunge, gunge, gunge, gunge, gunge);' if you are debugging the 'doesn't time out' path, the yoda means you can skip all the crap without scrolling to the end. – Martin James Jan 27 '16 at 14:36
  • 1
    @Lundin: Wile the dup included the same subject, maybe that one is more appropriate: http://stackoverflow.com/questions/148298/how-to-check-for-equals-0-i-or-i-0 – too honest for this site Jan 27 '16 at 14:39
  • @MartinJames How about `DWORD result = WaitForYadaYada ... ; if(result == WAIT_TIMEOUT)`? Too readable? :) – Lundin Jan 27 '16 at 14:39
  • 1
    @Olaf Generally it isn't a good idea to use closed questions as duplicates, because if they are indeed a duplicate it probably means that this question too should be closed. That being said, I think it is a fair question and not opinion-based since one occasionally encounters obfuscated code like this when maintaining old crap. – Lundin Jan 27 '16 at 14:42
  • @Lundin lol, sure, I'm often arguing that temp vars should be used more to improve debugging, so I guess I cannot argue too much over that one:) – Martin James Jan 27 '16 at 14:43
  • 1
    @Lundin: Not sure. The linked question has correct answers, which shows the subject has been handled already. It would be better to reopen that one and close this as dup. – too honest for this site Jan 27 '16 at 14:47
  • @MartinJames Indeed, it will yield the very same machine code anyhow. Any compiler will optimize away that temp variable. – Lundin Jan 27 '16 at 14:47
  • 1
    @MartinJames: Things become complicated with MSRA & other styleguides which disallow mixing statements and declarations. – too honest for this site Jan 27 '16 at 14:48
  • @Olaf Perhaps, although there's the C++ tag, and nothing is easy in C++... there's operator overloading and also C++ has a sane type system for equality operators, they evaluate to booleans rather than int. So I think C and C++ answers may be different here. Anyway, I've posted an answer here now, so I'm probably partial :) – Lundin Jan 27 '16 at 14:49
  • @Lundin: That question is tagged both. Anyway, I think the simple answer "do not!" applies to both (you know I'm very careful when it comes to "C/C++"). – too honest for this site Jan 27 '16 at 14:54
  • If I could go back in time to Bell Labs around, oh, 1970, I'd slap dmr silly for not making the assignment operator completely distinct from the equality operator (something like `:=` or similar). Then this entire class of bugs would never have existed. – John Bode Jan 27 '16 at 14:55
  • "decreases the readability" or not is more often about how the block/function looks. Assessing style of a single line of code `if ( 10 == val) {}` without showing its context prevents a quality assessment of its readability. – chux - Reinstate Monica Jan 27 '16 at 14:55
  • @JohnBode I use Delphi, (Pascal), C++ and C. Imagine how often I get assignments/compares wrong:( – Martin James Jan 27 '16 at 14:56
  • 1
    @JohnBode: Just tell me once you completed the time-machine. I'd also like to have a serious talk with some people. One with Wirth for being too dogmatic, thus burdening us now with those C legacies. – too honest for this site Jan 27 '16 at 14:56
  • We completed the time machine long ago. Here's from the crucial part of the firmware: `setjmp(today); if(C = !good) { longjmp(the_past, 1972); slap(dennis.ritchie); longjmp(today, 2016); }` Didn't work however :( And the person who wrote the original code forgot to use braces after `if` and we haven't seen him since. – Lundin Jan 27 '16 at 16:20

2 Answers2

6

It doesn't have to do with optimization, it's a trick used to avoid accidental assignment and it's called Yoda Convention or Yoda Conditions. It prevents accidental assignment because

if (value = 10)

would compile and would assign 10 to value which is not what you want if you meant if (value == 10) (although some compilers can warn about this and suggest extra parentheses to avoid the ambiguity), this

if (10 = value)

would not.

Since compilers can warn, and when you have experience this is a very uncommon mistake I would advice against this. Because it's difficult to read it and it doesn't feel natural. So be careful and use normal conditions like

if (value == 10)

and to be safe, enable warnings in your compiler to prevent the accidental assignment. See this is equivalent to talking like Yoda, like in this comment and you can see why in the natural language this is uncomfortable, it is too in the code.

Community
  • 1
  • 1
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
  • Many thanks for these explanations. – PascalDeLyon Jan 27 '16 at 14:43
  • `Since compilers can warn, and when you have experience this is a very uncommon mistake I would advice against this. Because it's difficult to read it and it doesn't feel natural. So be careful and use normal conditions` I happen to think Yoda Conditions are a great thing, and it has saved me a few times despite "being careful". I also think the "doesn't feel natural" argument against this is extremely weak. I think your answer would be better without pushing your opinions since the question wasn't "is this a good idea", or at least offering an unbiased view of the mild controversy. /flame – Nicu Stiurca Jan 27 '16 at 14:44
  • @SchighSchagh I think most good programmers think Yoda Conditions are bad. And if I see them in someone elses code I immediately close the text editor and stop reading. It is a matter of preference but I am just that way, crazy ... So if you think you should please downvote the answer. – Iharob Al Asimi Jan 27 '16 at 14:46
  • @SchighSchagh: Just ask some people on the street for similar natural language sentences. Harder to understand these are definitively. – too honest for this site Jan 27 '16 at 14:58
  • I use yodas frequently. I find them actually clearer than many 'conventional' conditionals and I don't have any problem with finding them in other devs. code. – Martin James Jan 27 '16 at 15:00
  • @MartinJames Like I said, a matter of preference. Some have good taste some others don't. Not trying to be offensive, it's an opinion and it's perfect to consider it wrong. About closing the text editor. Yesterday my partner sent something to install on a web server and I hated it so much that I wanted to kick my screen. And I rejected it of course, I know that it's not a natural thing or normal behavior but I can't help it. – Iharob Al Asimi Jan 27 '16 at 15:07
2

The original, historical reason is fear for the ancient, classic bug where you would mix up the = and == operators.

When dinosaurs walked the earth and C was a new language, programmers coming from other languages, most notably Pascal, were particularly prone to write this bug. Because in Pascal, comparison is done by = rather than ==.

To avoid that bug, some of the more confused dinosaurs therefore invented this particular coding style. Because if(10 = val) will not compile. This trick was informally known as the "Yoda conditions", after a Star Wars character who uses backwards, obfuscated language grammar.

Then around 1989, Borland came up with a smart solution to the problem: instead of having programmers make their programs unreadable, let's make a compiler warning for possibly incorrect assignment inside conditions! This was the end of the "Yoda conditions" and every half-decent compiler released since Turbo C has supported a warning for such accidental assignments.

If you encounter someone today, who still thinks this trick is smart, you therefore know that they are either a living dinosaur, or possibly Yoda, the jedi master. In either case you should probably not take any C programming advise from them. But you could ask them why they insist on using a compiler which is worse than Turbo C from 1989.

Lundin
  • 195,001
  • 40
  • 254
  • 396