+ 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?
5 Answers
+ 2
thank you so much Alex...
+ 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
+ 1
Try to learn something about writing clean code: Book by Robert martin -> Clean code
+ 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?
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.