【问题标题】:Whats happening in this for loop这个 for 循环中发生了什么
【发布时间】:2017-04-26 22:15:03
【问题描述】:

for 循环的第一条语句发生了什么?我似乎无法理解为什么 1 == 2 可以接受,因为它是比较而不是赋值。

char ch = 120;
unsigned char x = 1;
unsigned int y = 1;
for(1 == 2; ch > 0; ch++) {
  printf("%d\n", ch);
  x <<= 1;
  y *= 2;
}

【问题讨论】:

标签: c for-loop comparison-operators


【解决方案1】:

编译器将优化掉它只是一个无用的语句。 for 中的第一条语句不需要是赋值,它只是构建为简洁/可读的方式来循环一组值。您可以将for 循环扩展为while,它可能会更清晰:

1 == 2; // does nothing, likely emits compiler warning.
while( ch > 0 )
{
    printf("%d\n", ch);
    x <<= 1;
    y *= 2

    ch++;
}

如果你想对后迭代表达式使用 for 循环,但已经初始化了你的变量,你可以使用 null 语句作为第一个表达式:

for( ; ch > 0; ch++ ){ /* ... */ }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-12
    • 1970-01-01
    • 2015-10-16
    • 1970-01-01
    • 2018-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多