+ 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?

9th Jun 2019, 8:06 PM
Rishu Kumar
Rishu Kumar - avatar
8 Answers
+ 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.
9th Jun 2019, 9:08 PM
Cluck'n'Coder
Cluck'n'Coder - avatar
+ 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.
10th Jun 2019, 4:25 AM
Manoj
Manoj - avatar
+ 5
try printing just x without the loop am sure x will be 0
9th Jun 2019, 8:20 PM
āœ³AsterisKāœ³
āœ³AsterisKāœ³ - avatar
+ 4
Rishu Kumar that tells you the value of x is not a garbage value
9th Jun 2019, 8:56 PM
āœ³AsterisKāœ³
āœ³AsterisKāœ³ - avatar
+ 4
x is from 0 to -1 = 1 iteration (for x=0) šŸ¤”
10th Jun 2019, 4:39 PM
Sanjay Kamath
Sanjay Kamath - avatar
+ 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
10th Jun 2019, 6:52 PM
sree harsha
sree harsha - avatar
+ 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.
9th Jun 2019, 8:55 PM
Rishu Kumar
Rishu Kumar - avatar
+ 1
x is a global variable and has its default value as 0
12th Jun 2019, 7:28 AM
harsh anand
harsh anand - avatar