3

我正在处理该代码,我尝试使用x + 1而不是,++x结果是无限循环并且屏幕上打印了零。

这是代码:

#include <stdio.h>
int main(void){
  int x;
  for(x = 0; x <= 100; x + 1) //instead of ++x
    printf("%d\t",x);
  return 0;
}

我想知道这个动作......为什么编译器没有产生这样的错误,,,,实际发生了什么??!并且被x++视为x += 1?!

4

4 回答 4

9

您需要x更改 的值,否则您的循环将永远不会终止。如果只有x + 1,则在迭代结束时x + 1计算,但其结果值被丢弃。表达式的结果不存储在任何地方。所以x将保持为零,x <= 100并将保持真实,并且您的循环将永远继续。

如果您有以下任何一种情况:

x = x + 1
x += 1
x++
++x

自身的值x增加。这就是你需要的。

于 2013-08-25T09:51:51.120 回答
6

Although the basic structure of a for loop is like-

for(initialization; condition; increment or decrement)

But in its core part the "condition" part is treated only to control the loop behavior. So, if other two parts are syntactically correct, then compiler won't produce any error.

Since, x+1 is a valid C statement and the value of the x is not changing so it will go to an infinite loop for the condition [x <= 100 => 0 <= 100] being true forever.

Again, x++ or ++x both treated as x = x + 1 when used independently. But, x++ is actually Post-increment operator, while ++x is Pre-increment operator. That means, the with ++x, the value of the x will be incremented first and then assigned to x. Whereas, the current value of x will be used for the entire statement in x++ and then x will be incremented and assigned with new value. Look at the following example-

    #include<stdio.h>
    void main()
    {
        int x=5;
    /* Post & Pre-Increment used independently */
        x++;
        printf("x : %d", x);

        ++x;
        printf("\nx : %d", x);

    /* Used with printf() statement */
        printf("\nPre-increment of x: %d", ++x);

        printf("\nPost-increment of x: %d", x++);

        printf("\nPost-increment effect on x: %d", x);
    }

Output:

x : 6
x : 7
Pre-increment of x: 8
Post-increment of x: 8
Post-increment effect on x: 9

I Hope my explanation have made you understand, if still not you can reply me back.

于 2013-08-25T09:55:38.900 回答
5

表达式x + 1应该x = x + 1在 for 循环中,所以正确:

for(x = 0; x <= 100; x + 1) 
                      ^ 
                      doesn't increment x

无限循环!

作为:

for(x = 0; x <= 100; x = x + 1) 

或者

for(x = 0; x <= 100; x += 1)  // or simply x++ or ++x

编译器没有产生这样的错误,因为x + 1它是一个有效的表达式(但它不是你想要的)。

所以, x += 1, x++or++x不仅加一x而且修改 的值x

于 2013-08-25T09:46:36.790 回答
1

您的方法并不完美,因为它肯定会增加 x 的值,但是在分配时,它会失败。所以你的陈述应该涵盖你的所有要求。

尝试使用

#include <stdio.h>
int main(void){
int x;
for(x = 0; x <= 100; x = x + 1)
    printf("%d\t",x);
return 0;
}

或者你可以使用

#include <stdio.h>
int main(void){
int x;
for(x = 0; x <= 100; x++)
    printf("%d\t",x);
return 0;
}

除了x++(后增量),您还可以使用前增量(++x)。该表达式x = x + 1;也可以写成x += 1;which 是嵌入增量赋值的简写方法。这不仅仅是关于增量,您还可以使用其他运算符。

x -= 3;
x *= 2;
于 2013-08-25T09:52:46.047 回答