Why am I not able to access the global variable using extern? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why am I not able to access the global variable using extern?

https://code.sololearn.com/cBPk9ojl6YDf/?ref=app Why isn't a value changing to 5 after using the extern keyword?

12th Jul 2021, 11:20 AM
Srinath
11 Answers
+ 2
The extern keyword indicates that this variable was defined elsewhere, for example, when creating large projects, all global variables can be stored in a separate file, and subroutines are scattered across other files. That is, extern essentially copies the variable. This increases the compilation speed. In your case, extern is not required, "main" and this how sees the given variable.
12th Jul 2021, 12:27 PM
Solo
Solo - avatar
+ 2
Mahmoud Osman Because you declared two different variables, one global, the other local, and it will throw an error because the local variable is not used. Write "return printf("%d%d", a, get_a());" and there will be an output: 65
13th Jul 2021, 9:07 PM
Solo
Solo - avatar
+ 1
Verstappen Because you are re-initialising a by 6 so your output will be 6
12th Jul 2021, 11:44 AM
A͢J
A͢J - avatar
+ 1
Vasiliy oh now I get it, thankss!!
12th Jul 2021, 12:49 PM
Srinath
+ 1
Verstappen, I'm glad I was able to help you, you can mark my answer as the best ☺️
12th Jul 2021, 3:31 PM
Solo
Solo - avatar
+ 1
Vasiliy haha alright done!!
12th Jul 2021, 3:52 PM
Srinath
+ 1
😉
12th Jul 2021, 3:56 PM
Solo
Solo - avatar
+ 1
Why not to : int a = 5; int get_a (void) { return a; } int main(void) { int a = 6; return printf ("%d", get_a()) ; }
13th Jul 2021, 7:50 PM
Mahmoud Osman
Mahmoud Osman - avatar
+ 1
Vasiliy done, now I get it clearly
15th Jul 2021, 11:50 AM
Srinath
0
Jazz ohh i get it but still this can be achieved even without extern right? as a's value is going to be reinitialized again Or is extern a keyword for declaring variables in different files? Please explain.
12th Jul 2021, 12:14 PM
Srinath
0
Mahmoud Osman why did you use return in main()?
15th Jul 2021, 11:49 AM
Srinath