Ganesh Kundapur said:
Hi,
int x = 10;
int main ()
{
int x = 5;
??? /* Access the global x here */
}
How to access the global x within main?
As you have it, you cannot. But with a scope adjustment:
#include <stdio.h>
int x = 10;
int main(void)
{
{
int x = 5;
}
printf("%d\n", x); /* prints 10 */
return 0;
}
or a 'back door' access via a pointer:
#include <stdio.h>
int x = 10;
int main(void)
{
int *p = &x; /* must come *before* declaration of 'x' below */
int x = 5;
printf("%d\n", *p); /* prints 10 */
return 0;
}
Or more sensibly, change the name of one of the 'x's
Also, globals are generally not recommended without
a compelling reason to define them.
Is your question only academic, or is there a particular
problem you're trying to solve?
-Mike