C language: if() with no else(): using braces fails

前端 未结 5 989
后悔当初
后悔当初 2021-01-29 06:47

I\'m confused on need for braces after IF() expression. When using IF(){...}ELSE{...} I\'m used to using braces around both IF and ELSE blocks. But when I use no ELSE block it

5条回答
  •  渐次进展
    2021-01-29 06:51

    Both the if and else clauses control only the immediately following statement. Your code, indented correctly, is actually:

    #include "simpletools.h"
    int main()
    {
      while(1)
      {
        print("button = %d\n", input(3));
        if(input(3) == 1) 
          high(14); 
        pause(50);
        low(14);
        pause(50);
      } //while
    }   // main
    

    The fact that two statements may be on the same line is irrelevant; the if still only controls a single statement. If you want to control two or more statements, you must wrap them in a "compound statement" by using braces:

    #include "simpletools.h"
    int main()
    {
      while(1)
      {
        print("button = %d\n", input(3));
        if(input(3) == 1) {
          high(14); 
          pause(50);
        } else {
          low(14);
          pause(50);
        }
      } //while
    }   // main
    

    Since the else must immediately follow the if's controlled statement, inserting it after your two-statement line without braces won't work.

提交回复
热议问题