Question

I'm a little Confused about this code result:

#include <stdio.h>
int g;
void afunc(int x)
{
     g = x; /* this sets the global to whatever x is */
}

int main(void)
{
    int g = 10;    /* Local g is now 10 */
    afunc(20); /* but this function will set it to 20 */
    printf("%d\n", g); /* so this will print "20" */

    return 0;
}

Why the result is 10 Not 20 ?

Was it helpful?

Solution 2

Calling afunc changes the global g, and main retains its local g.

Entering a function doesn’t swap its scope with the global scope. Each function* has its own scope.

* Among other things

OTHER TIPS

The local variable g shadows the global g.

If you want the printf() to show 20, you have to shadow your local variable g with a declaration of the global one you want to print:

int main(void)
{
    int g = 10;            /* Local g is now 10 */
    afunc(20);             /* Set global g to 20 */
    printf("%d\n", g);     /* Print local g, "10" */
    {
        extern int g;      /* Use global g */
        printf("%d\n", g); /* Print global g, "20" */
    }
    return 0;
}

If you get rid of the int in

int g = 10;

then main will also be referring to the same global variable as afunc is.

This is called variable shadowing

Have NOT modified your code, but have adjusted your comments to indicate what the code is doing. By the way, commenting your code is a really good idea and makes for better lab scores!! signed, A Former Graduate TA

#include <stdio.h>
int g;       /* define a global variable
void afunc(int x)
{
     g = x; /* this sets the global to whatever x is */
}

int main(void)
{
    int g = 10;    /* Define and set a Local g to 10 */
    afunc(20);     /* This function sets global x to 20 */
    printf("%d\n", g); /* this prints local g "10" */

    return 0;
}

To think about this "look-up" from main to global storage. You see local g before global g, thus local g is used.

In both the occasions, though the variable name appears to be same, they 2 are referring 2 different memory area. The variable g declared outside any function got stored in the RAM memory area, and the variable g declared inside main is got stored in stack area. So the invocation of afunc() is changing the variable g stored in RAM but again printing the variable g(stored in stack) which got declared locally.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top