DEV Community

Sujith V S
Sujith V S

Posted on • Updated on

Variable scope in C programming.

A variable scope can determine which variable can be accessed from which region of the program. In C programming there are two types of scope,

  • Local variable scope
  • Global variable scope

Local variable scope

Any variable that is declared inside a function is local to it. it cannot be accessed from outside that function.

#include <stdio.h>

void addNumbers(int number1, int number2){
    int result = number1 + number2;
}

int main() {
    addNumbers(5, 6);
    printf("Result = %d", result);
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

This code shows an error.
error: 'result' undeclared (first use in this function).

In the above code we are trying to access the variable result from the main function. Since we declared this variable in the addNumbers function, it is not possible to access result variable from main function. Because, the result variable is local to addNumbers function.

Global variable scope

These are variables which are declared outside the function. Therefore, this variables can be accessed globally(can be accessed from any part of our code).

int result;

void addNumbers(int number1, int number2){
    result = number1 + number2;
}

int main() {
    addNumbers(5, 6);
    printf("Result = %d", result);
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Here the result variable is declared outside the main function and addNumber function.

Top comments (0)