Nested if statement question

Discussion in 'Programmer's Corner' started by ecka333, Oct 6, 2010.

  1. ecka333

    Thread Starter Active Member

    Oct 1, 2009
    76
    0
    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?
     
  2. cheezewizz

    Active Member

    Apr 16, 2009
    82
    10
    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
    Code ( (Unknown Language)):
    1.  
    2. if(a == 1)
    3. {
    4.     if(b == 1)
    5.     {
    6.         c = 1;    
    7.     }
    8. }
    9.  
    but this is the same as
    Code ( (Unknown Language)):
    1.  
    2. if((a == 1) && (b == 1))
    3. {
    4.     c = 1;
    5. }
    which is a little better than having loads of if's IMO...
     
  3. DonQ

    Active Member

    May 6, 2009
    320
    11
    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:
    Code ( (Unknown Language)):
    1.   c = (a==1)&&(b==1) ? 1 : TheValueIfFalse;
    which you can also nest if you need to.
     
  4. ecka333

    Thread Starter Active Member

    Oct 1, 2009
    76
    0
    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.
     
Loading...