Search code examples
iphoneif-statementwarningsconditional-statementsassignment-operator

warning in the PageControl sample code: Using the result of an assignment as a condition without parentheses


I'm trying to understand the way UIPageControl works. SO I downloaded this sample code from Apple UIPageControlSampleCode It runs fine but there is a warning (Using the result of an assignment as a condition without parentheses) at the if-statement in the following code:

- (id)initWithPageNumber:(int)page 
{
    if (self = [super initWithNibName:@"MainView" bundle:nil])
    {
        pageNumber = page;
    }
    return self;
}

Now my question is: why would the developer do something like this? making an assignment inside of an if-statement condition? Is it a mistake?


Solution

  • An assignment operator (=), except for performing the assignment, also returns the assigned value. This is so you can do stuff like

    a = b = 1;
    

    Which for the compiler is the same as writing

    a = (b = 1);
    

    This means that when doing

    self = <some init function>;
    

    You can check if the init succeeded by putting the assignment in an if statement. If it succeeded it returns a valid pointer, which is not zero which means the condition of the if statement is true. If the init fails, it returns nil which is actually zero, so there is no point in continuing the rest of the initialization.

    The reason for the warning is that it's easy to accidentally use (=) in an if statement instead of (==):

    if ( a = 1 ) // Should be a == 1
    {
        // Do important stuff
    }
    

    So the compiler is trying to protect you from this mistake.

    For this reason I prefer making the condition explicit, in your example:

    if ((self = [super initWithNibName:@"MainView" bundle:nil]) != nil)