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

前端 未结 5 943
后悔当初
后悔当初 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 07:07

    A single statement follows the if. If you need multiple statements, they must be combined into a single compound statement.

    if (input(3) == 1)
        high(14);
    pause(50);
    low(14);
    pause(50);
    

    executes both pause functions and low regardless of what input returns. Where you put the newlines does not affect how C parses the code. You need braces to combine the 4 function calls into a single compound statement:

    if (input(3) == 1) {
        high(14);
        pause(50);
        low(14);
        pause(50);
    }
    

    The absence or presence of an else clause does not change anything, except that

    if (input(3) == 1)
        high(14);
    pause(50);
    else ...
    

    would result in an error, since the else is not joined to any if statement; the if concludes with the single statement high(14), and the pause(50) is a separate statement altogether, so the else is out of place.

提交回复
热议问题