Back to: C Tutorials For Beginners and Professionals
Local vs Global Variables in C Language with Examples
In this article, I will discuss the Local vs Global Variables in C Language with Examples. Please read our previous articles, discussing the Functions Return by Value and Return by Address in C Language with Examples. At the end of this article, you will understand what local and global variables are in C and the differences between them with examples.
Scope Rule in C Language:
In C, all variables have a defined scope. The region of the program over which the declaration of an identifier is visible is called the scope of the identifier. The scope relates to the accessibility, the period of existence, and the boundary of usage of variables declared in a statement block or a function.
Local Variables in C Language:
Variables that are declared inside a function or block are called local variables. They can be used only by statements inside that function or block of code. Local variables are not known to function outside their own. They have several key characteristics:
- Scope: Local variables are only accessible within the function or block in which they are declared. This means they cannot be accessed or modified by other functions or outside of their defining block.
- Lifetime: The lifetime of a local variable is limited to the duration of the function call in which they are defined. They are created when the function or block is entered and are destroyed when it is exited.
- Initialization: The system does not automatically initialize local variables, meaning they contain garbage values if not explicitly initialized. It’s a good practice always to initialize local variables before use.
- Memory Allocation: They are typically allocated on the stack, though this can depend on the compiler and the system architecture.
- Usage: They temporarily store information within a function and help make the function more self-contained and less dependent on external variables.
Example to Understand Local Variable in C:
#include <stdio.h> void functionExample() { int localVariable = 5; // A local variable printf("Local variable value is %d\n", localVariable); } int main() { functionExample(); // printf("%d", localVariable); // This would cause an error because localVariable is not accessible here return 0; }
In this example, localVariable is a local variable inside functionExample. It cannot be accessed in main or any other function.
Global Variables in C Language:
In the C programming language, global variables are declared outside of any function. These variables are accessible from any function within the same file or other files if the global variable is declared with the extern keyword. A global variable is available for use throughout your entire program after its declaration. Here are some key points about global variables in C:
- Scope: Global variables have a program-wide scope, meaning they can be accessed from any part of the program after their declaration.
- Lifetime: They are allocated memory for the entire lifetime of the program, meaning they exist from the start of the program until the program terminates.
- Declaration: Global variables are typically declared at the top of a file, outside of any functions, and are initialized to default values (such as zero for integers) if not explicitly initialized.
- Usage: They are used when multiple functions need to access the same data or when data needs to be preserved between function calls.
- Extern Keyword: To use a global variable in a different file than the one where it was declared, the extern keyword is used in the other file to provide a declaration (not definition) of the variable.
- Best Practices: While global variables can be useful, they are generally discouraged in modern programming practices due to their potential to create dependencies and complexities in the code, making it harder to debug and maintain.
- Initialization: Global variables can be initialized with a value when declared. If not initialized, numeric global variables are automatically initialized to zero, and pointers are initialized to NULL.
Example to Understand Global Variable in C:
Creating a simple program in C that demonstrates the use of global variables is straightforward. In this example, I will show you a basic program that uses a global variable to store a number, which different functions then access and modify.
#include <stdio.h> // Global variable declaration int globalVar = 10; // Function to display the global variable void display() { printf("Value of globalVar in display function: %d\n", globalVar); } // Function to modify the global variable void modify() { globalVar = 20; printf("Value of globalVar in modify function: %d\n", globalVar); } int main() { printf("Value of globalVar in main function before modification: %d\n", globalVar); modify(); // Modify the global variable display(); // Display the modified global variable return 0; }
In this Program:
- globalVar is declared as a global variable initialized to 10.
- The display function prints the current value of globalVar.
- The modify function changes the value of globalVar to 20 and then prints it.
- In main, the value of globalVar is first printed, then modify is called to change its value, and finally display is called to show the changed value.
Local and Global Variables with the Same Name in C Language:
In C, it is possible to have local and global variables with the same name. This situation is often referred to as “shadowing.” When a local variable in a function shares the same name as a global variable, the local variable “shadows” or “hides” the global variable within the scope of that function. Any reference to the variable name within the function will refer to the local variable, not the global one. Here is an example to illustrate this:
#include <stdio.h> // Global variable declaration int myVar = 10; // Function with a local variable of the same name void myFunction() { int myVar = 20; // Local variable, shadows the global variable printf("Value of myVar inside myFunction: %d\n", myVar); // This will print 20 } int main() { printf("Value of myVar in main before calling myFunction: %d\n", myVar); // This will print 10 myFunction(); printf("Value of myVar in main after calling myFunction: %d\n", myVar); // This will still print 10 return 0; }
In this Program:
- myVar is declared globally with a value of 10.
- myFunction has a local variable also named myVar, but it is assigned a value of 20. Inside myFunction, any reference to myVar refers to the local variable, not the global one.
- In the main function, before and after the call to my function, myVar refers to the global variable.
This program illustrates how local and global variables with the same name can coexist in C. However, avoiding such naming conflicts’s generally good practice to prevent confusion and potential errors in larger, more complex programs.
Differences Between Local and Global Variables in C:
- Visibility: Local variables are visible only within the function where they are declared, whereas global variables are visible throughout the program.
- Lifetime: Local variables exist only while the function is executing, while global variables exist throughout the program’s execution.
- Scope and Accessibility: Local variables have a limited scope confined to their function or block, while global variables are accessible throughout the program.
- Memory Allocation: Different memory allocation strategies (stack for local, data segment for global).
Example to Understand Local and Global Variables in C:
#include <stdio.h> int globalVar = 10; // Global variable void myFunction() { int localVar = 20; // Local variable printf("Local Variable: %d\n", localVar); printf("Global Variable in Function: %d\n", globalVar); } int main() { printf("Global Variable in Main: %d\n", globalVar); myFunction(); return 0; }
In this example, globalVar is accessible both in main() and myFunction(), while localVar is only accessible within myFunction().
Best Practices
- Minimize Use of Global Variables: Overuse can lead to code that is hard to understand and maintain. It’s generally better to pass data to functions explicitly through arguments.
- Initialize Local Variables: Always initialize local variables to avoid undefined behavior.
- Global Variable Naming: Use distinctive names for global variables to avoid name conflicts with local variables.
Understanding the distinction between local and global variables is essential for writing efficient and maintainable C code. It helps manage memory effectively and avoids bugs related to variable scope and lifetime.
In the next article, I will discuss Block Scope in C Language with Examples. In this article, I try to explain local vs. global variables in C language with examples. I hope you enjoy this article, Local Vs Global Variables in C Language with Examples. I would like to have your feedback. Please post your feedback, questions, or comments about this article.