Warning :suggest parentheses around assignment used as truth value

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

  1. roublesaha macrumors newbie

    Joined:
    Dec 22, 2008
    #1
    Hi
    I am using this snippet of code

    void * handle_;

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

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

    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

    Joined:
    Jul 25, 2006
    #2
    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:

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

    Code:
    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

    Joined:
    Apr 24, 2008
    #3
    It is also because the statement

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

    Code:
    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