Reputation: 53
Here's an example regarding local and global variables. The result of this program displays the value of the global variable g
.
What if I want to print/use the value of the global variable?
#include <stdio.h>
/* global variable declaration */
int g = 20;
int main ()
{
/* local variable declaration */
int g = 10;
printf("value of g = %d\n", g);
return 0;
}
Upvotes: 2
Views: 246
Reputation: 45654
Only for globals, you can just call another function to access it (and maybe return a pointer).
For all cases of shadowing, you can use a pointer you saved earlier.
Still, the best option is the simplest one: Just change the identifier in the inner scope to avoid shadowing.
Upvotes: 1
Reputation: 1
Delete the local variable and declare it as global... Since the global variable has scope throughout the program, you can use it in any function of the program. But if you still want to declare the same variable locally then the local variable dominates the variable declared globally.
Upvotes: -1
Reputation: 19864
The scope of the variable int g=10;
is just within main()
so you can print the global variable anywhere apart from main()
like calling some API as shown below.Else if you want to print it within main()
then you need to have a pointer to your global variable and dereference it to get the value. The below approach doesn't introduce any new variable .
#include <stdio.h>
/* global variable declaration */
int g = 20;
void print_global()
{
printf("value of g = %d\n", g);
}
int main ()
{
/* local variable declaration */
int g = 10;
printf("value of g = %d\n", g);
print_global();
return 0;
}
Upvotes: 1
Reputation: 54551
This is not possible, the local g
shadows the global one. However, in practice this is more a feature than a limitation since it means you don't have to worry about choosing variable names distinct from globals, and, of course, you can easily control your local names to allow access to a like-named global.
Upvotes: 3
Reputation: 108988
Use a pointer to the global variable
#include <stdio.h>
/* global variable declaration */
int g = 20;
int main ()
{
int *pg = &g;
/* local variable declaration */
int g = 10;
printf("value of g = %d\n", *pg);
return 0;
}
Upvotes: 4