花括号和范围在C中如何工作? [英] How do curly braces and scope wоrk in C?

查看:107
本文介绍了花括号和范围在C中如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试在业余时间学习一些C语言.我对Java有一定的经验,因此我习惯于用大括号限制变量的作用域.但是我有点困惑,因为好像Brian W. Kernighan/Dennis M. Ritchie的书"The C Programming Language"并没有使用很多花括号,我认为使用花括号是正常的(从Java角度).例如.本书中代码1.6所在的位置:

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;

从Java的角度来看,由于没有花括号,我习惯于仅执行第一条语句,但是缩进表明所有内容都将运行(如果,否则,如果不是).

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).

所以我要问的是:这里将运行什么,为什么会运行? if,if,if和else是否都在while循环的范围内?有没有要参考的约定,我可以阅读以更好地理解它?预先感谢.

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.

推荐答案

whileifelse ifelse后跟一个语句.该语句可以是C的实际行,也可以是block语句(用大括号括起来). ifelse ifelse被视为一个块.

The while, if, else if, and else are followed by a single statement. This statement can be an actual line of C, or a block statement (surrounded by braces). The if, else if, and else are considered as one block.

因此使用花括号,这将是等效的:

So using braces, this would be the equivalent:

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

这篇关于花括号和范围在C中如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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