C变量的困惑 [英] C variable confusion
问题描述
在我的任务,我看到这行中使用的一个:
In one of my assignments I am seeing this line used:
int index = -1, k;
林不知道如果我们有对一个变量的条目发生了什么。
究竟什么是变量指标召开时,它有两个条目?
Im not sure what is happening when there are to entries for the one variable. What exactly is the variable "index" holding when it has two entries?
推荐答案
在C,逗号操作符,
拥有的低的precedence比赋值运算符 =
。因此,前pression
In C, the comma operator ,
has lower precedence than the assignment operator =
. As such, the expression
int index = -1, k;
被解析为
//The parentheses are not legal in C, but it's what the parser does.
int ((index = -1), k);
您看到,该行声明类型的变量 INT
。其中第一个被称为首页
并初始化为 1
,第二个叫<$ C $ ç> K 和未初始化。
You see, that the line declares variables of type int
. The first one of which is called index
and is initialized to -1
, the second one is called k
and is not initialized.
您可以在这里找到操作precedences的一个很好的概述:结果
https://en.wikipedia.org/wiki/Operators_in_C_and_C%2B %2B#Operator_ precedence 结果
需要注意的是逗号操作符是在该列表中的最后一个!
You can find a good overview of the operator precedences here:
https://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence
Note that the comma operator is the very last one in that list!
同样的,你可能会看到C- code这样的或类似的:
Likewise, you may see C-code like this, or similar:
if(condition) foo += 7, doSomething();
while(i += 2, i < 42) ...;
这相当于
if(condition) {
foo += 7;
doSomething();
}
i += 2;
while(i < 42) {
...
i += 2;
}
但更简洁(许多C程序员喜欢简洁!)。此外,在这两种情况下的逗号操作符的作用是融合两件事情到一个单一的语句,避免写一个完整的块 {}
和prevents增量<重复code> I + = 2 。
but much more terse (many C programmers like terseness!). Again, in both cases the comma operator serves to fuse two things into a single statement, which avoids writing a full block {}
and prevents repetition of the increment i += 2
.
无论是逗号操作符的这种使用是好是坏是品味和环境的问题。但你可以一定会找到它的所有可能的用途在野外。
Whether such uses of the comma operator are good or bad is a matter of taste and circumstance. But you can be certain to find all possible uses of it in the wild.
这篇关于C变量的困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!