C语言:if()没有else():使用大括号失败 [英] C language: if() with no else(): using braces fails

查看:1384
本文介绍了C语言:if()没有else():使用大括号失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对IF()表达式之后需要大括号感到困惑。
当使用IF(){...} ELSE {...}时,我习惯在IF和ELSE块周围使用大括号。
但是当我没有使用ELSE块时,它没有大括号,并且使用大括号失败:

工作:IF()...

失败:IF(){。 ..}

下面的示例,这是针对微控制器的?

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 works with no braces and fails with braces:
works: IF()...
fails: IF(){...}
Example below, this is for a microcontroller

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


推荐答案

如果,后面会有一个语句。如果您需要多个语句,则必须将它们合并为一个复合语句。

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

执行暂停函数和无论输入返回什么。放置换行符的位置不会影响C解析代码的方式。你需要大括号将4个函数调用组合成一个复合语句:

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);
}

缺少或出现 else 子句不会改变任何东西,除了

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

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

会导致错误,因为 else 未加入任何 if 语句; 如果以单一陈述高(14)结束,而暂停(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.

这篇关于C语言:if()没有else():使用大括号失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆