Warning :suggest parentheses around assignment used as truth value

Discussion in 'Mac Programming' started by roublesaha, Jan 8, 2009.

  1. roublesaha macrumors newbie

    Dec 22, 2008
    I am using this snippet of code

    void * handle_;

    if (handle_ =dlopen("/System/Library/Frameworks/DiskArbitration.Framework/Versions/A/DiskArbitration",RTLD_NOW))

    else if (handle_ =dlopen("/System/Library/PrivateFrameworks/DiskArbitration.Framework/Versions/A/DiskArbitration",RTLD_NOW))

    But i am getting the warning :
    "suggest parentheses around assignment used as truth value" for the first line i,e the for the "for" loop....can somebody help me to get rid of this warning..:confused:
  2. kpua macrumors 6502

    Jul 25, 2006
    First off, it's generally bad form to have side-effects in if() statements.

    However, sometimes it's the simplest way to code what you mean (though I don't think it is in your example necessarily). When you do have an assignment in an if statement, GCC generally expects something like this:

    if ( (foo = bar()) != NULL )
    Notice the extra parentheses around the assignment. GCC suggests you use the parentheses to avoid the following error:

    if ( foo = bar() != NULL )
    which wouldn't check for the value assigned to foo being equal to NULL, but rather assign the boolean (bar() != NULL) to foo.

    It's also customary and generally more clear to have the explicit boolean check in there, so that's why GCC expects this.
  3. Sander macrumors 6502

    Apr 24, 2008
    It is also because the statement

    if (a = b) {...}
    is correct C (assign b to a and check for non-zero), but most often people really meant

    if (a == b) {...}
    Since assignment inside the if() is the exception, GCC issues a warning about it. Also for future readers of your code, the extra parentheses indicate "yes, I really mean assignment here".

Share This Page