0

I'm currently trying to learn some C in my spare time. I have some experience in Java, and I'm therefore used to limit scoping of i.e. variables with curly braces. But I'm a bit confused, as it seems like Brian W. Kernighan/Dennis M. Ritchie's book "The C Programming Language" doesn't use a lot of curly braces, where I would assume it's normal to use them (from a Java perspective). E.g. 1.6 in the book where the code is:

while((c = getchar())) != EOF)
    if (c >= '0' && c <= '9')
        ++ndigit[c-'0'];
    else if() /*and so forth...*/
        ++nwhite;
    else
        ++nother;

From a Java perspective I'm used to that only the first statement would be run then, because of the lack of curly braces, but the indentation suggests that everything will run (if, else if and else).

So what I'm asking is: What would run here, and why would it run? Are if, else if and else all in the scope of the while loop? Are there any conventions to refer to, that I can read to try to understand it better? Thanks in advance.

4

4 回答 4

4

whileif和后跟一个语句else ifelse该语句可以是 C 的实际行,也可以是块语句(用大括号括起来)。、ifelse ifelse视为一个块。

所以使用大括号,这将是等价的:

while((c = getchar())) != EOF) {
    if (c >= '0' && c <= '9') {
        ++ndigit[c-'0'];
    }
    else if() {  /*and so forth...*/
        ++nwhite;
    }
    else {
        ++nother;
    }
}
于 2013-08-06T13:55:28.797 回答
2

在 C 中,与在 Java 中一样,anìf和 awhile有一个语句作为其主体,并且if可以有一个可选else子句,其中一个语句作为其主体。在大多数可以有一个语句的地方,你可以有一个语句块,它是一个用大括号括起来的语句列表。这在 C 中与在 Java 中没有什么不同。

为了避免歧义,如果有两个 if 和一个 else,则定义 else 以引用最后一个。IE。

if(a) x if(b) y else z

被定义为

if(a) x { if(b) y else z }

并不是

if(a) x { if(b) y } else z

这里,x、y 和 z 是语句——它们也可以是语句块。

然而,说了这么多,省略大括号很容易出错,因此许多编码指南建议始终使用花括号。

于 2013-08-06T14:06:21.710 回答
1

如果 if 语句不包含花括号,则最多可以在其后内联一个分号,它会自动假定花括号如下:

while((c = getchar())) != EOF){
    if (c >= '0' && c <= '9')
    {
        ++ndigit[c-'0'];
    }
    else if() /*and so forth...*/
    {
        ++nwhite;
    }
    else
    {
        ++nother; 
    }
 }

所以这是有效的:

 while(true) i++;

这不应该是有效的:

 while(true) i++; break; printf("hello");

 if(true) printf("Hello"); break; 
于 2013-08-06T13:54:35.730 回答
1

您可以将if/else if/else指令视为一个块 - 它们不能真正被分割,else不能单独存在。

在旁注中,当您遇到类似的情况时,有时会感到困惑

if(something)
   if (somethingOther)
     ....
else
   .....

如果您的代码足够长,您可能会混淆在哪里附加 this else,所以最好总是使用大括号。如评论中所述,else始终附加到“最近的” if

于 2013-08-06T13:57:30.410 回答