简体   繁体   English

为什么while循环被执行多次?

[英]Why the while loop is executed more than once?

I have got a question in the interview for which I had to find out the output of the following code. 我在面试中遇到了一个问题,我必须找出以下代码的输出。 I tried but it was not correct. 我试过但不正确。 Please explain the following code. 请解释以下代码。

#include<stdio.h>
int main()
{
    int x=0,a;
    while(x++ < 5)
    {
        a=x;
        printf("a = %d \n",a);
        static int x=3;
        printf("x = %d \n",x);
        x+=2;
    }
    return 0;
}

Output: 输出:

a = 1
x = 3
a = 2
x = 5
a = 3
x = 7
a = 4
x = 9
a = 5
x = 11

Can anyone please explain whats going on here? 有谁能解释一下这里发生的事情?

The loop conditional expression x++ < 5 uses the x declared outside the loop. 循环条件表达式x++ < 5使用在循环外声明的x The statement x += 2; 陈述x += 2; is not affecting the x declared outside the loop because static int x=3; 不会影响在循环外声明的x ,因为static int x=3; hides the previous declaration of x . 隐藏了之前的x声明。

In other words, all modifications to x after the statement static int x=3; 换句话说,语句static int x=3;之后对x所有修改static int x=3; is not affecting the x used in loop controlling expression. 不影响循环控制表达式中使用的x

It is because x++ returns the current value of x and then is incremented. 这是因为x++返回的当前值x ,然后递增。

In the first iteration, 在第一次迭代中,

while(x++ < 5)

is same as 和...一样

while(0 < 5)

Then,after the condition has been checked, x will be incremented. 然后,在检查条件之后, x将递增。 Thus the value of a is the incremented value of x . 因此, a的值是x的递增值。 The static x ,shadows(hides) the x declared outside the loop and hence, static x ,阴影(隐藏)在循环外声明的x ,因此,

x+=2;

affects the static x and not the outer one. 影响static x而不影响外部static x The variable x declared in the loop,since it is static exists as long as the program does and will not be lost once it goes out of scope. 变量x在循环中声明,因为它是static ,只要程序执行就会存在,并且一旦超出范围就不会丢失。 It will be initialized to 3 and 2 will be added in each iteration of the loop to it. 它将被初始化为3,并且在循环的每次迭代中将它添加到它。

This is equivalent to: 这相当于:

int x=0,a;
int y=3;
while(x++ < 5)
{
    a=x;
    printf("a = %d \n",a);
    printf("x = %d \n",y);
    y+=2;
}

The second x was hiding the first x . 第二个x隐藏了第一个x

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM