+ 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];

2nd Nov 2021, 8:02 AM
Nariman Tajari
Nariman Tajari - avatar
14 Respostas
+ 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
2nd Nov 2021, 8:12 AM
Rishi
Rishi - avatar
+ 4
Nariman Tajari well, I would say it'd be better to choose the right option as "undefined" or something similar to it
2nd Nov 2021, 1:07 PM
Rishi
Rishi - avatar
+ 2
Nariman Tajari well, I run it on Sololearn and got some negative number with really high magnitude
2nd Nov 2021, 8:18 AM
Rishi
Rishi - avatar
+ 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?
3rd Nov 2021, 2:57 PM
Mehran
Mehran - avatar
+ 2
Mehran how? Do global variables get auto initialization in C?
3rd Nov 2021, 2:59 PM
Rishi
Rishi - avatar
+ 2
Mehran ooh yeah tnx very much =)
3rd Nov 2021, 3:18 PM
Rishi
Rishi - avatar
+ 1
Yes rishi well answered but i donno why sololearn offers "0"as answer.
2nd Nov 2021, 8:13 AM
Nariman Tajari
Nariman Tajari - avatar
+ 1
Nariman Tajari I think your shared code is incomplete.
2nd Nov 2021, 9:41 AM
A͢J
A͢J - avatar
+ 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
2nd Nov 2021, 9:46 AM
A͢J
A͢J - avatar
+ 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.
2nd Nov 2021, 9:53 AM
Nariman Tajari
Nariman Tajari - avatar
+ 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.
2nd Nov 2021, 10:18 AM
A͢J
A͢J - avatar
+ 1
Here, this is your complete code, run it and see for yourself =) https://code.sololearn.com/c9a8p94VyowS/?ref=app
2nd Nov 2021, 12:32 PM
Rishi
Rishi - avatar
+ 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.
2nd Nov 2021, 12:46 PM
Nariman Tajari
Nariman Tajari - avatar