Search code examples
objective-cif-statementbooleanios6cgrect

If (BOOL) in Objective C: unused variable


In an implementation of a CGRect, I attempt this:

BOOL didStartPressing = NO;
if ( didStartPressing) {int nmax=5;}
else{int nmax=500;}

for (int n=1; n<nmax; n=n+1){ *... working code that draws some circles ....*     }

This gives yellow warnings about "unused variable nmax" in the first part above and red warnings about "use of undeclared variable nmax." for the for loop. If however I simply replace the first three lines above with

int nmax=500; 

I get a lovely picture that I drew in CGRect.

Greatest of thanks for help, as I'm complete noob up against the hard wall of learning curve.


Solution

  • You've limited the scope of nmax to the braces after the if and the else. So you have two variables with that name, neither of which is visible to the for loop. To solve, move the declaration to the outer scope and simply assign to the variable in the if/else scopes:

    int nmax = 0;   // the = 0 is optional in this case because all code
                    // paths assign a value to nmax
    BOOL didStartPressing = NO;
    if (didStartPressing) {
        nmax=5;
    } else {
        nmax=500;
    }
    
    for (int n=1; n<nmax; n=n+1) {
        /*... working code that draws some circles ....*/
    }