+ 1
What is the output of this code and why??
int i,a[10]; For(i=4;i<9;i+=3) {i=i-2;} Cout<<a[8];
14 ответов
+ 8
After correcting and completing, this code will produce different output in different runs. It's output is undefined. Why? It's simple, you are printing the value a[8] but you didn't assign anything to it. So garbage value will be printed.
In other words, it'll print based on the random bits in that memory location because you didn't modify it to have your own value
But if the variable is global variable, then it'll print 0. The reason for it is below, tnx to @Mehran
https://stackoverflow.com/questions/14049777/why-are-global-variables-always-initialized-to-0-but-not-local-variables
+ 4
Nariman Tajari well, I would say it'd be better to choose the right option as "undefined" or something similar to it
+ 2
Nariman Tajari well, I run it on Sololearn and got some negative number with really high magnitude
+ 2
If "a" is defined in global scope, its value isn't garbage. all its indices are 0.
Are you sure it was inside the function?
+ 2
Mehran how? Do global variables get auto initialization in C?
+ 2
Mehran ooh yeah tnx very much =)
+ 1
Yes rishi well answered but i donno why sololearn offers "0"as answer.
+ 1
Nariman Tajari
I think your shared code is incomplete.
+ 1
Nariman Tajari
You will get garbage value because i never would be 8
Because after i = 6, i would be 9 so "for" loop will not execute because 9 < 9 is false
+ 1
A͢J - S͟o͟l͟o͟H͟e͟l͟p͟e͟r͟ yes true but i donno why sololearn offers "0" as a output.
I guess in some quizes question's last answer designed like this just for fun.
+ 1
Nariman Tajari
Not for fun because garbage value may change everytime so they just put 0 in quizzes which makes more sense instead of some garbage value.
+ 1
Here, this is your complete code, run it and see for yourself =)
https://code.sololearn.com/c9a8p94VyowS/?ref=app
+ 1
Yes i know rishi but A͢J - S͟o͟l͟o͟H͟e͟l͟p͟e͟r͟ said the sololearn did it as it seems to be more senseful.