C Conceptual Questions/beginner
Problem:
Explain the difference between local and global variables.
Solution:
Understanding the Problem:
In C programming, local and global variables are two types of variables based on their scope and lifetime. Understanding the distinction between them helps in designing effective programs where the control of variable access is essential.
Code Implementation:
#include <stdio.h>
int globalVar = 10; // Global variable
void myFunction() {
int localVar = 5; // Local variable
printf("Local variable: %d", localVar);
printf("Global variable: %d", globalVar);
}
int main() {
myFunction();
return 0;
}
Code Explanation:
- Global Variables:
int globalVar = 10;
declares a global variable that is accessible throughout the entire program, including all functions. It is declared outside of any function and retains its value across function calls. - Local Variables: Inside the
myFunction()
function,int localVar = 5;
declares a local variable. This variable is accessible only withinmyFunction()
and ceases to exist once the function terminates. - Scope: The global variable
globalVar
is accessible both insidemain()
andmyFunction()
, while the local variablelocalVar
is only accessible withinmyFunction()
. - Lifetime: A global variable remains in memory for the duration of the program’s execution, while a local variable is created when the function is called and destroyed when the function finishes.
Thus, local variables have a limited scope and are used within specific functions, whereas global variables are used when a value needs to be shared across different parts of the program.