I have a program that has 3 global variables, 2 functions f() and g() and a main.
It looks like this:
int a, b, c;
int f(int x)
{
return a * x;
}
int g()
{
int c;
c = a;
a = b;
b = c;
return c;
}
int main()
{
int x, y;
a = 2;
b = 3;
c = 4;
x = f(a);
y = g();
printf("%d %d %d %d %d\n", x, y, a, b, c);
return 0;
}
I know that in the g function since a c variable is declared then the c used inside of it is the new c and not the global variable.
But what I do not understand is why g() was able to modify the global variables.
Can't we only modify variables using pointers in these situations?
I don't really understand why a and b were swapped, my printf gives me: 4 2 3 2 4
Thanks
CodePudding user response:
Global variables can be accessed directly, there is no need to use pointers.
As for why a and b were swapped, look at your g
function:
local_c = a // this is equal to 2;
a = b // this is equal to 3;
b = c // this is eqaul to 2, originally a;
CodePudding user response:
Global variables have a global scope, meaning they can be accessed and modified anywhere throughout the program. And in this case there is no need to use pointer .
And to see why a and b where swapped you should check out your g function :
c = a // now c = 2 ;
a = b // now a = 3 ; a get the amount of b ;
b = c // now b = 2 ; now b get the first amount of a and it is clear a & b are exchanged ;