Are nested ifs different from &&?
Hi everyone
Not a broken code thing, more a request for a lesson in theory (I got my problem fixed)
In my match 3 experimenting I had a bit of broken code that looked like this
//if the nextPiece matches the startPiece
if(nextPiece.matchValue == startPiece.matchValue)
{
//safety check that the piece isn't already in the list
if (!matches.Contains(nextPiece))
{
//add the next game piece to our list of matches
matches.Add(nextPiece);
}
else //the next piece isn't a match
{
//break out of the loop
break;
}
}
The problem was resolved by replacing the nested ifs with this line!
if (nextPiece.matchValue == startPiece.matchValue && !matches.Contains(nextPiece))
My issue is, aren't these just the same?! I always thought they were both performing the same function, that both conditions have to be met. But my fix tells me otherwise.
Can some experience code guru explain to me the difference between a nested if and using &&? I need to get my head around this to make sure it doesn't happen again
Answer by Hellium · Jul 22, 2019 at 12:47 PM
if( A )
{
if( B )
{
// Do something
}
}
And
if( A && B )
{
// Do something
}
Are strictly identical. You won't notice any performance difference
HOWEVER
if( A )
{
if( B )
{
// Do something
}
else
{
// Do something else
}
}
And
if( A && B )
{
// Do something
}
else
{
// Do something else
}
Are different.
In the 2nd case, Do something else
will run if A
OR B
are false, while in the 1st case Do something else
will run if A
is true AND B
is false. The two approaches are semantically different.
Of course! It was the else! Thanks so much. Can't believe I didn't get that.
Really appreciate you taking the time, Hellium
I guess this question is answered so i'll accept this answer on your behalf