Nested if statement question

Thread Starter

ecka333

Joined Oct 1, 2009
76
I am trying to program pic microcontroller. Now i faced with nested if statement. (Compiler-Mikroc from mikroelektronika). Here i wrote simplified code:
if(a==1){if(b==1){c=1;};}.
We have variables:a=0, b=1. Whether a variable c will be changed to 1 or not?
 

cheezewizz

Joined Apr 16, 2009
82
No C won't be changed because it won't go into the first if statement as A = 0. By the way you don't need the semi-colon after the braces i.e it should be
Rich (BB code):
if(a == 1)
{
    if(b == 1)
    {
        c = 1;    
    }
}
but this is the same as
Rich (BB code):
if((a == 1) && (b == 1))
{
    c = 1;
}
which is a little better than having loads of if's IMO...
 

DonQ

Joined May 6, 2009
321
but this is the same as
Rich (BB code):
if((a == 1) && (b == 1))
{
    c = 1;
}
which is a little better than having loads of if's IMO...
Especially since C 'short-cuts' the test. If the first test is false, it doesn't even need to do the second test, so it doesn't.

Realize some "C-type languages" don't necessarily do this, but if it is "real C", then it is a feature of the language.

For simple assignments, I prefer this construct:
Rich (BB code):
  c = (a==1)&&(b==1) ? 1 : TheValueIfFalse;
which you can also nest if you need to.
 

Thread Starter

ecka333

Joined Oct 1, 2009
76
Ok, thank you both for ansfers. I had doubt for the if statement, because i had read somewhere, that nested loops are executed from the innermost loop, so i thinked maybe inner loop will be executed, but outer-not.

The variant, given by DonQ:
if((a == 1) && (b == 1))
{
c = 1;
}

is not good for me, because in reality my loop has more variables.
 
Top