+ 4
Why is the loop getting executed one time in the following code?
int x; int main(){ for(;x>=0;--x){cout<<"a";} return 0; } If the value given to x was 0 then the loop would have been executed once but there is no value given to x then how come the loop is running and there is no error! can someone please explain this?
8 ответов
+ 3
In your example, 'x' is a global variable and has a static storage duration. Static variables are initialized to 0 by default. Had 'x' been a local variable it would contain garbage values.
+ 10
As it gets executed for first time the value of x gets decremented and becomes -1 which doesn't satisfy the given condition of x>=0. So the loop gets executed only once.
+ 5
try printing just x without the loop am sure x will be 0
+ 4
Rishu Kumar that tells you the value of x is not a garbage value
+ 4
x is from 0 to -1 = 1 iteration (for x=0) 🤔
+ 4
since x is an external or globlal scope variable
default value of global variable is 0
Moreover it can be used any where and any no of times till end of the program
In loop 0>=0 is true 1 time loop is executed
next -1>=0 is false the control will come out from loop
that is the reason the mentioned loop will be executed only once
+ 1
*Asterisk* yes it came out to be zero but isn't when a new variable is declared then initially it has some garbage value.
+ 1
x is a global variable and has its default value as 0