+ 1

What is the value of local variable 'x' at the end of main function?

int x= 5; int main() { int x=x; return 0; } The answer given was undefined.... Please explain me why the value of 'x' at the end of main function is not 5?

30th Mar 2018, 3:41 PM
Suraj Jha
Suraj Jha - avatar
5 Answers
+ 2
thank you so much Alex...
30th Mar 2018, 4:29 PM
Suraj Jha
Suraj Jha - avatar
+ 1
when there is a local variable with the same name as a global you need :: to tell the compiler that you want to access the global variable instead of the local. Here is an example: https://code.sololearn.com/coJsTd8dqSgb/?ref=app
30th Mar 2018, 3:54 PM
Alex
Alex - avatar
+ 1
Try to learn something about writing clean code: Book by Robert martin -> Clean code
30th Mar 2018, 4:02 PM
***
*** - avatar
+ 1
Alex what I understood is— "before defining the local variable the value of x will remain global (x). ie. we don't need ' :: ' to specify it as a global. But after defining local variable we need to specify whether it gonna take the value of local(x) or global(x).... in this code the local (x) is defined without assigning any value to it therefore it is undefined?" is it right?
30th Mar 2018, 4:18 PM
Suraj Jha
Suraj Jha - avatar
0
Yes that's all right. And if you don't specify which variable it should take it takes the one from the local scope. Which in this example is the main function.
30th Mar 2018, 4:21 PM
Alex
Alex - avatar