DEV Community

Sujith V S
Sujith V S

Posted on • Edited on

1 1 1 1 1

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.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more