Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many conditions can an if check for

How many conditions can an if check for? EG,

if(a==1 && b==1 && c==1 && ... && n==1)

I know this could probably be solved simply by nesting ifs and then it wouldn't be an issue how many. But frankly, I'm curious and can't seem to find how many it will take.

In addition, since I have your attention anyway, is there any difference in efficiency between

if(a==1 && b ==1)

And

if(a==1)
    if(b==1)
like image 904
Heather T Avatar asked Feb 24 '15 15:02

Heather T


2 Answers

There isn't a limitation to the amounth of conditional statements in an if. Also, there's no performance improvements in either of the two blocks.

The biggest difference between the two is that you don't have control over which condition failed with the first one.

Example:

if(a==1 && b==1) {
    //do something
} else {
    //no way to tell which one failed without checking again!
}

other one:

if(a==1) {
    if(b==1) {
        //do something
    } else {
        // 'b' failed (meaning: b is not equal to 1)
    }
} else {
    // 'a' failed
}
like image 198
Gerralt Avatar answered Oct 10 '22 07:10

Gerralt


There is no explicit limit, as far as I know. The practical limit is when readability becomes an issue.

The actual code-wise limit is probably caused by the fact that a Java method can only contain about 64 KiB of bytecode.

Your last two code blocks do the same thing (assuming there's only a single code block or statement after them). They would only be different if an else were involved.

like image 20
Joachim Sauer Avatar answered Oct 10 '22 06:10

Joachim Sauer