Why is the while loop executed more than once?

I have a question in an interview for which I had to find a way out of the following code. I tried, but it was wrong. 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 someone explain what is going on here?

+4
source share
3 answers

In conventional terms, the cycle x++ < 5used x, declared outside the loop. The statement x += 2;does not affect xdeclared outside the loop because it static int x=3;hides the previous declaration x.

In other words, all changes in the xafter statement static int x=3;do not affect the ones xused in the loop control expression.

+2
source

, x++ x .

while(x++ < 5)

while(0 < 5)

, , x . , a x. static x, () x, , , ,

x+=2;

static x, . x ​​ , static, , . 3 2 .

+2

:

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

x x.

+1

Source: https://habr.com/ru/post/1569819/


All Articles