Scope
Published Jan 29, 2025
Contribute to Docs
In C, scope defines the region of a program where a variable can be accessed. Variables in C are categorized into local and global scopes based on their accessibility.
Local Scope
Variables declared inside a function or block have local scope, meaning they are accessible only within that function or block.
Syntax for local scope
return_type function_name() {
// Variable with local scope
data_type variable_name = value;
// Code that uses the variable
...
}
data_type
: Represents the type of the variable.variable_name
: Name of the variable used in the code.value
: Value assigned to the variable.
Global Scope
Variables declared outside of any function have global scope and can be accessed and modified from any function within the program.
Syntax for global scope
data_type variable_name = value;
// Global variable (declared outside any function)
return_type function_name() {
// Code that can access the global variable
}
Example
The example demonstrates variable scope in C, where globalVar
has global scope (accessible throughout the program), while localVar
has local scope (accessible only within myFunction
):
#include <stdio.h>// Global variableint globalVar = 100;void myFunction() {// Local variableint localVar = 10;// Accessing both local and global variablesprintf("Local variable inside myFunction: %d\n", localVar);printf("Global variable inside myFunction: %d\n", globalVar);}int main() {// Accessing the global variableprintf("Global variable inside main: %d\n", globalVar);// Calling the function which accesses both local and global variablesmyFunction();return 0;}
The code above produces this output:
Global variable inside main: 100Local variable inside myFunction: 10Global variable inside myFunction: 100
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.