August 29, 2008
C/C++/Objective-C programmers:

marco:

Tired of these bugs?

if (x = 5) { /* Oops, accidentally set x to 5 */ }

Use GCC’s -Wparentheses option, which will generate warnings whenever you do this. (In Xcode, it’s in Project Info: GCC 4.0 - Warnings: Missing Braces and Parentheses.)

If you actually intend for the assignment to be the evaluated value in a conditional, just give it an extra set of parentheses:

if ( (x = 5) ) { /* That's better */ }

The extra spaces are optional. That’s just the style I like for these constructs to make it very clear during code reading that you intended to do this.

I think I had one of this in a test at university, is a classic one :)

  1. do-nothing reblogged this from marco
  2. tonblr reblogged this from benjaminstein and added:
    That doesn’t help if they are both variables! e.g. (y=x)
  3. jhalickman reblogged this from marco and added:
    I am personally a big fan...just changing your programming style
  4. brendn reblogged this from benjaminstein and added:
    Benjamin Stein has weighed...accidental assignment debate:
  5. amelios reblogged this from marco and added:
    It’s especially handy when using null/nil!...Some people don’t
  6. brendn reblogged this from marco and added:
    Earlier today, Marco showed us how...fix accidental assignment bugs:
  7. benjaminstein reblogged this from marco and added:
    ALWAYS putting the constant on the LHS....x) will never compile, arguments or not!
  8. mandel reblogged this from marco and added:
    I think I had one...test at university, is a classic one :)
  9. marco posted this