[英]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.