Idiomatic C/C++: Avoiding Assignment Vs. Equality Errors

This is a bit of idiomatic c/c++, that is to say that this isn’t part of any standard, it is just “the way things are done” in c/c++. Ever made an error in a conditional using the assignment operator (=) instead of the equality operator (==)? I know I have, but not so much anymore. The trick is that when you are comparing a variable to a constant to put the constant first. This way if you mess up you will get a compiler error stating that you can’t assign to a constant. This is much preferable to a potentially subtle bug that will no doubt bite you when a deadline is looming. So instead of:

int x;
if( x == 5)
    ; //Do something

do:

int x;
if( 5 == x)
    ;//Do something

3 Responses to “Idiomatic C/C++: Avoiding Assignment Vs. Equality Errors”

  1. matt Says:

    brilliant.

  2. Chris Says:

    Yeah, I prefer this method, but my boss hates it because, fair enough, it does make your code less simple and readable.

  3. admin Says:

    Indeed, this can make your code a little obtuse when you’re reading it. I find that even if I don’t do it this way remembering that I should makes me avoid the error anyway.

Leave a Reply