Global Variables in C
Global Variables in C
Global Variables in C
Global variables are defined outside a function, usually at the top of a program.
Global variables hold their values throughout the lifetime of a program and they can
be accessed inside any of the functions defined for the program.
If a function accesses and modifies the value of a global variable, then the updated
value is available for other function calls.
If a variable defined in a certain file, then you can still access it inside another code
module as a global variable by using the extern keyword. The extern keyword can
also be used to access a global variable instead of a local variable of the same name.
data_type variable_name;
#include <stdio.h>
int main(){
https://www.tutorialspoint.com/cprogramming/c_global_variables.htm 1/5
6/16/24, 12:40 PM Global Variables in C
/* actual initialization */
a = g * 2;
printf("Value of a = %d, and g = %d\n", a, g);
return 0;
}
Output
When you run this code, it will produce the following output −
#include <stdio.h>
int function1();
int function2();
int main(){
function1();
printf("Updated value of Global variable g = %d\n", g);
function2();
https://www.tutorialspoint.com/cprogramming/c_global_variables.htm 2/5
6/16/24, 12:40 PM Global Variables in C
return 0;
}
int function1(){
g = g + 10;
printf("New value of g in function1(): %d\n", g);
return 0;
}
int function2(){
printf("The value of g in function2(): %d\n", g);
g = g + 10;
return 0;
}
Example
In this example, we declared a global variable (x) before the main() function. There
is another global variable y that is declared after the main() function but before
function1(). In such a case, the variable y, even thought it is a global variable, is not
available for use in the main() function, as it is declared afterwards. As a result, you
get an error.
#include <stdio.h>
https://www.tutorialspoint.com/cprogramming/c_global_variables.htm 3/5
6/16/24, 12:40 PM Global Variables in C
int function1();
int main(){
int y = 20;
int function1(){
printf ("Value of Global variable x = %d y = %d\n", x, y);
}
Example
In this C Program, we have a global variable and a local variable with the same
name (x). Now, let's see how we can use the keyword "extern" to avoid confusion −
#include <stdio.h>
// Global variable x
int x = 50;
int main(){
https://www.tutorialspoint.com/cprogramming/c_global_variables.htm 4/5
6/16/24, 12:40 PM Global Variables in C
// Local variable x
int x = 10;{
extern int x;
printf("Value of global x is %d\n", x);
}
return 0;
}
Output
When you run this code, it will produce the following output −
Value of global x is 50
Value of local x is 10
https://www.tutorialspoint.com/cprogramming/c_global_variables.htm 5/5