我不明白正在打印的结果

Log*_*oga -1 c

这个程序打印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;
}
Run Code Online (Sandbox Code Playgroud)

Jea*_*bre 6

这个程序打印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;
}
Run Code Online (Sandbox Code Playgroud)

第二个条件:如果你退出printf注释,你将执行最后一个i+=2;,否则你将执行两个i += 2语句.

因此,执行了2个添加:一个添加1,一个添加2.

3 + 1 + 2 = 6
Run Code Online (Sandbox Code Playgroud)

请注意,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;
     ^
Run Code Online (Sandbox Code Playgroud)

作为结论:即使只有一条指令,也要用花括号来保护你的条件.这可以保护您免受:

  • 之后可能由其他人添加的代码,意图在条件中添加但失败.
  • 定义2个或更多指令且不遵循该do {} while(0)模式的宏:只有宏中的第一条指令由if