【发布时间】:2018-11-11 06:25:55
【问题描述】:
如果i等于1,则在此语句之后,
while (i++ <= 10){}
i 被视为 2,即在块中评估之前递增。
但是如果用在switch中,
switch(i++){}
i 在块中递增之前被评估。
为什么i++ 的这些案例表现不同?
例子:
对于 While 情况:
#include <stdio.h>
int main()
{
int age = 20;
while (age++ <= 65)
{
if ((age % 20) == 0)
{
printf("You are %d years old\n", age);
}
}
return 0;
}
我希望这会打印出来:
You are 20 years old
You are 40 years old
You are 60 years old
对于开关盒:
#include <stdio.h>
int main()
{
int i = 0;
while (i < 3)
{
switch (i++)
{
case 0:printf("print 0");
case 1:printf("print 1");
case 2:printf("print 2");
default:printf("Oh no!");
}
putchar('\n');
}
return 0;
}
【问题讨论】:
-
怎么样?我不明白。
-
这两种情况应该是一样的。请出示minimal reproducible example 并解释您认为结果应该是什么,以及您看到的不同之处。
-
@Barmar 我在主帖下为这两种情况添加了示例。
-
将代码放在问题中,而不是在远程站点。
-
注意:您所有的案例标签都缺少
break。
标签: c while-loop switch-statement post-increment