Supertecnoboff
Supertecnoboff

Reputation: 6606

if statement code warning - code will never be executed - iOS

I have an iOS app with a few different if statements. However something is wrong with Xcode, it keeps saying that my code will never be executed... this is silly.... its just an if statement, how an earth can NOT be executed.

Basically my if statements are checking for an ID integer number, some of the numbers result in the same outcome, thus my if statements are checking for multiple numbers.

Here is my code:

if (num == (200 || 201 || 202 || 210 || 211 || 212 || 221 || 230 || 231 || 232)) {
      // Run image type 1 setup here...  
}

else if (num == (300 || 442 || 881 || 882 || 890 || 900)) {
      // Run image type 2 setup here....
}

And the else-if statements continue on. But for some weird reason Xcode actually thinks my that my code wont be executed.

What an earth have done wrong here?

Thanks, Dan.

Upvotes: 0

Views: 9139

Answers (1)

Tommy
Tommy

Reputation: 100622

if (num == (200 || 201 || 202 || 210 || 211 || 212 || 221 || 230 || 231 || 232))

is the same statement as:

if (num == x)

where x is:

(200 || 201 || 202 || 210 || 211 || 212 || 221 || 230 || 231 || 232)

Which is always 1. So you've written the same test as:

if(num == 1)

That's also the subject of the else if. Since the else if cannot be true unless the if is true, it will never be executed.


An example switch statement that does what you want, based on the fact that case statements fall through, could be:

switch(num) {
    case 200: case 201: case 202: /* ... etc ... */ case 232:
        // image type 1 here
    break;

    case 300: case 442: /* ... etc ... */
        // image type 2 here
    break;
}

Upvotes: 5

Related Questions