views:

314

answers:

3

I've tried searching the documentation and the internet as best as I'm able, but I haven't been able to get the Xcode compiler to issue a warning if the assignment operator is used in an if statement.

I'm coming from RealBasic, where I've got an extremely strong habit of typing this sort of comparison:

if x = 5 then ...

In C, of course, that syntax assigns x the value of 5 then tests the result to see if it's nonzero, and the "correct" operator is:

if (x == 5) { ... }

I've found several mentions that the compiler should be able to warn if there is an assignment made in an if comparison, but I cannot find how to turn it on in Xcode 3.1/gcc. I found the -pedantic option, but that didn't seem to generate the warning.

Since I've spent a fair amount of time twice now tracking down bugs that turned out to be "=" instead of "==", I'd like the help of a warning.

I know that I can do this instead (which will cause a compiler error):

if (5 = x) { ... }

...but that requires changing ingrained coding habits, too. Not to mention that it looks clumsy and backward.

Thanks!

+1  A: 

This may be of help to you.

ennuikiller
See my own answer to the question below for details.
Rob
+1  A: 

You're looking for the -Wall option I think.

int main(void) {

    int x = 5;
    if ( x=5) { 
    }
    return 0;
  }

$ g++ -pedantic x.cc 
$ g++ -Wall x.cc 
x.cc: In function ‘int main()’:
x.cc:7: warning: suggest parentheses around assignment used as truth value

This link describes how to enable options through the Xcode GUI

Glen
+1  A: 

The link in ennuikiller's answer did lead to what I needed.

Here's a bit more information for anyone who might find this in the future:

  • The compiler warning is "Missing braces and parentheses", or -Wparentheses.

  • The warning is turned on by choosing Get Info for the current target in Xcode.

  • As I finally found out, the iPhone Simulator SDK does not show this compiler option.

  • Switching the SDK to iPhone Device will show the GCC 4.2 Warnings section, which includes "Missing braces and parentheses".

  • After turning on that option in the iPhone Device SDK, switching back to the Similator shows that a "User-Defined" build setting has been added: GCC_WARN_MISSING_PARENTHESES = "YES".

  • If an assignment is really desired in an if statement, you can double the parentheses to avoid the warning.

(Double-parentheses example:)

if ((x = 5)) { ... }

The warning works like a charm, though it does dislike Apple's standard:

if (self = [super init]) { ... }

I'll probably leave those as-is, though if I end up with a huge amount of them in a project, I'll either double the parenthesis or break out the assignment into a separate line.

Thanks!

Rob