What is the output for this static scoping problem and how it works

#include <stdio.h>

int a,b;

void print () {

printf("%d %d", a, b);

}

int fun1() {

int a, c;

a = 0; b = 1; c = 2;

return c;

}

void fun2() {

int b;

a = 3; b = 4;

print();

}

int main() {

a = fun1();

fun2();

}

the output should be 3,1.
first,we should learn the golbal scope and local scope.
#include <stdio.h>

int a,b;
//the variable a,b is in the global scope,u can change value of a,b directly.
void fun1(){
a=4;
b=3;
}
int main(){
fun1();
printf("%d %d",a,b);//the output will be 4,3
}
however,when u delcared the new variable(same name with the global variable) in the function(local scope),it will cut the global connection.
int a,b;
//the variable a,b is in the global scope,u can change value of a,b directly.
void fun2(){
int a,b;//new variables,same name with global variables,cut the global connection with global variables
a=4;
b=3;
}
int main(){
fun1();
printf("%d %d",a,b);//the output will be undefined,coz u don’t assign any value to it.
}

1 Like

The output will be 3, 1.

Variable scoping in language like C is pretty simple. A variable declared outside any block will be considered as global variable. It means it is accessible to all the functions.
When a variable declared inside a function, it scope is limited only to function itself. The variable will be available while function is executing and disappear when functions terminates.

If you have a global variable named int apple; and also a variable with same name int apple in a function block. The function always use the function variable not global variable. A function variable also called local variable in context to the function.

Static

1. A static variable inside a function keeps its value between invocations.
2. A static global variable or a function is "seen" only in the file it's declared in 

#include <stdio.h>

void foo()
{
    int a = 10;
    static int sa = 10;

    a += 5;
    sa += 5;

    printf("a = %d, sa = %d\n", a, sa);
}


int main()
{
    int i;

    for (i = 0; i < 10; ++i)
        foo();
}

This print

a = 15, sa = 15
a = 15, sa = 20
a = 15, sa = 25
a = 15, sa = 30
a = 15, sa = 35
a = 15, sa = 40
a = 15, sa = 45
a = 15, sa = 50
a = 15, sa = 55
a = 15, sa = 60
1 Like