Variable scope in C programming.

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 

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

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

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;
}

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

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
meet-your-new-intern!-five-tips-to-manage-chatgpt

Meet your new intern! Five tips to manage ChatGPT

Next Post
7-generative-ai-prompts-to-help-your-content-marketing-workflows

7 Generative AI Prompts To Help Your Content Marketing Workflows

Related Posts