Why result is 8 ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

Why result is 8 ?

int y; for(int y = 2; y <= 6; y += 2) {} cout <<y;

2nd Oct 2018, 8:47 AM
Izaak GOLDSTEIN
Izaak GOLDSTEIN - avatar
2 Answers
+ 4
The result being 8 is coincidence, because the y that is being outputted has not been initialized before and therefore has some garbage value that was stored in that memory cell before. The loop parameter y is only a local variable and doesn't actually affect the previously declared y, it has its own scope limited to the loop's body.
2nd Oct 2018, 8:58 AM
Shadow
Shadow - avatar
+ 3
Yes, I understand now
22nd Dec 2018, 7:47 PM
Izaak GOLDSTEIN
Izaak GOLDSTEIN - avatar