[英]code between curly brackets and change in values of variables
int main(void) {
int i = 2, k = 3, a;
i++;
++k;
{
int i = 0;
i = k++;
printf("%d,%d,", i, k);
}
printf("%d,%d", i, k);
getchar();
return 0;
}
Why this code produces output "4,5,3,5" why not "4,5,4,5"? 为什么此代码产生输出“ 4,5,3,5”,为什么不产生“ 4,5,4,5”? Why when I trace code by f7 key c++ then it goes first printf then second printf().
为什么当我通过f7键c ++跟踪代码时,它先进入printf,然后进入第二printf()。 So according to this value of variable must remain 4, then why it give value of i variable 3 in second printf() function?
因此,根据该变量的值必须保持为4,那么为什么要在第二个printf()函数中给出i变量3的值呢?
Second printf
doesn't "see" that i
declared as int i =0;
第二个
printf
没有“看到” i
声明为int i =0;
, because that i
is in another scope created by your curly braces. ,因为
i
在您的花括号创建的另一个作用域中。
So, the second printf
takes the first i
, which was declared (and defined) as int i =2
and in the next line incremented to 3
with i++
. 因此,第二个
printf
使用第一个i
,该i
被声明(并定义为) int i =2
并在下一行用i++
递增为3
。
By the way, code indentation is your friend (and ours too:). 顺便说一句,代码缩进是您的朋友(也是我们的朋友)。
Because curly braces delimits blocks, and in C variables are local to blocks. 因为花括号分隔了块,并且在C语言中变量是块的局部变量。
So the second i
is local to the inner block and different to the first which is local to the function main
. 因此,第二个
i
是内部块的局部,而不同于第一个i
是函数main
局部。
Take a look to this commented version of your code: 看一下这段代码的注释版本:
main(){
int i =2,k=3,a;
i++; // i = 3
++k; // k = 4
{
int i =0; // Lets call it i', then i' = 0 (it is different to i)
i=k++; // i' = k = 4, then increment k so k = 5
printf("%d,%d,",i,k); // Prints i', k: "4,5,"
}
printf("%d,%d",i,k); // Prints i, k: "3,5"
getch();
}
Curly braces in C
define block scope. C
花括号定义块范围。 So the i
in the block delimited by the curly braces is different from the one outside it. 因此,用花括号分隔的块中的
i
与外面的大括号不同。 I am tweaking your code a little bit and adding comments where helpful. 我会稍微调整您的代码,并在有帮助的地方添加注释。
// main should return int. void type should be explicit in the parameter list
int main(void) {
int i = 2, k = 3, a;
i++; // i is 3
++k; // k is 4
{ // block scope starts
int i = 0; // not the same as the previous i
i = k++; // block level i is 4 as k is 4
printf("%d, %d", i, k); // prints 4, 5
} // block scope ends
printf("%d, %d", i, k); // prints 3, 5
getchar(); // getch is nonstandard. use getchar instead
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.