[英]I don’t understand the results that are getting printed
该程序打印6
。
如果我取消注释//printf("yes");
行然后它打印8
,但不是yes
。
如果我删除第一个i++;
并将该行留空,它会打印7
。
如果我删除第二个i++;
它打印5
。
错误是什么?
int main () {
int i = 3;
if (!i)
i++;
i++;
if (i == 3)
//printf("yes");
i += 2;
i += 2;
printf("%d", i);
return 0;
}
这个程序打印 6 并且由于误导性缩进而很难得到。
它目前相当于:
int main ( ) {
int i = 3;
if (!i)
{
i++;
}
i++; // this is executed whatever the previous if
if (i==3)
//printf("yes");
{
i+=2; // could be executed because printf was commented, but isn't because of the value of i
}
i+=2; // executed whatever the previous if
printf("%d", i);
return 0;
}
第二个条件:如果您将printf
注释掉,您将执行最后一个i+=2;
, 否则你将执行两个i += 2
语句。
所以执行了 2 次加法:1 次加 1,1 次加 2。
3 + 1 + 2 = 6
请注意, gcc -Wall
在这些情况下会产生奇迹(更准确地说-Wmisleading-indentation
)。 在您的代码上:
test.c: In function 'main':
test.c:6:1: warning: this 'if' clause does not guard... [-Wmisleading-indentatio
n]
if (!i)
^~
test.c:8:5: note: ...this statement, but the latter is misleadingly indented as
if it is guarded by the 'if'
i++;
^
test.c:10:1: warning: this 'if' clause does not guard... [-Wmisleading-indentati
on]
if (i==3)
^~
test.c:13:5: note: ...this statement, but the latter is misleadingly indented as
if it is guarded by the 'if'
i+=2;
^
作为结论:即使只有一条指令,也要始终使用花括号保护您的条件。 这可以保护您免受:
do {} while(0)
模式的宏:只有宏中的第一条指令受if
条件限制我相信您的困惑是因为 C 允许您将大括号从if
语句中去掉,但只有紧随其后的语句才算作if
块内。
if (!i)
i++;
i++;
这和这个是一样的。
if (!i) {
i++;
}
i++;
如果您来自缩进是语法的 Ruby 或 Python,这可能会非常令人困惑。
虽然离开大括号很方便,但它也是引入错误的好方法。 永远不要使用此功能。
因为在“if”语句之后没有大括号,所以只有它们之后的行是有条件的。 缩进什么也没做!
选项 1 答案 = 6:
int main ( )
{
int i = 3; //i==3
if (!i) i++; // !3 = False Never Executed
i++; // i==4
if (i==3) i+=2; // i!=3, Never Executed
i+=2; // i==6
printf("%d", i);
return 0;
}
选项 1 答案 = 8:
int main ( )
{
int i = 3; //i==3
if (!i) i++; // !3 = False Never Executed
i++; // i==4
if (i==3) printf("yes"); // i!=3 Never Executed
i+=2; // i==6
i+=2; // i==8
printf("%d", i);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.