c - 在什么情况下我可以在 C 中省略花括号?

标签 c

我正在阅读著名的 K&R 书籍并被 1.6 中的示例所困扰。

#include <stdio.h>
/* count digits, white space, others */
main()
{
    int c, i, nwhite, nother;
    int ndigit[10];
    nwhite = nother = 0;

    for (i = 0; i < 10; ++i)
        ndigit[i] = 0;

    while ((c = getchar()) != EOF)
        if (c >= '0' && c <= '9')
            ++ndigit[c-'0'];
        else if (c == ' ' || c == '\n' || c == '\t')
            ++nwhite;
        else
            ++nother;

    printf("digits =");

    for (i = 0; i < 10; ++i)
        printf(" %d", ndigit[i]);

    printf(", white space = %d, other = %d\n", nwhite, nother);
}

这里为什么while语句可以在没有花括号的情况下工作?我知道如果块中只有一个语句,那么它们可以被省略。但在我看来 if...else if...else 不是一个单一的陈述。谁能给我解释一下?

最佳答案

while 的语法声明是:

while ( expression ) statement

在 C 语法中,语句是:
statement:
    labeled-statement
    compound-statement
    expression-statement
    selection-statement
    iteration-statement
    jump-statement

并且选择语句定义为:
selection-statement:
    if ( expression ) statement
    if ( expression ) statement else statement
    switch ( expression ) statement

所以你可以看到 if .. else if .. else本身就是一个陈述。

您可能还会注意到复合语句本身就是一个语句,例如,这个块:
{
    statement1;
    statement2;
}

也是一种说法。

关于c - 在什么情况下我可以在 C 中省略花括号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28100304/

相关文章:

c - 按长度排序,在 c 中具有稳定性

c++ - 如何在 C++ 中从 void* 数组中有效地解压 float、int16、int32 等数据?

c - 将文件中的字符串读取到数组中

c - C语言的FIFO读取和删除

c - 编写 vargarg C 预处理器宏,它调用其他宏及其每个参数等等

c - Socket发送二进制数据而不是文本数据

C 到 MIPS - 指令引用未定义 QTSpim

c++ - C 和 C++ 中的结构中数组初始化

c - 从函数中重新分配结构中的动态数组

c - 如何将 32 位图像上传到服务器端像素图