Variable Scope in C: The Complete Beginner’s Guide
Variable Scope in C: The Complete Beginner’s Guide

Variable Scope in C: The Complete Beginner’s Guide

Explore global scope, local scope, and block scope variables, along with their lifetimes, to write efficient and maintainable code.

Understanding the scope of a variable in C

The scope rules of a language are the rules that determine in which part(s) of the program, a particular section of the code or data present would be known and accessed.

What is the scope of a variable in C?

  • In C programming, the scope of a variable refers to the region of the program where the variable is accessible or visible. Consequently, this delineation determines precisely where in the program the variable can be used and accessed.
  • Consequently, the scope determines where in the program the variable can be used and accessed. There are primarily three types of scope in C:
  • Global Scope
  • Local Scope
  • Block Scope

Global Scope Variables in C

  • Variables declared outside of any function, typically at the beginning of the program, have global scope.
  • Variables are accessible from within functions, as well as from any other area of the program, ensuring their availability across different sections of the code.
  • Global variables retain their values throughout the lifetime of the program.
  • The scope referred to as file scope is also known as global scope because it operates for the entire program.

For Example:

C
#include <stdio.h>

int globalVariable = 10; // Global variable

void function() {
    printf("Global variable inside function: %d\n", globalVariable);
}

int main() {
    printf("Global variable in main: %d\n", globalVariable);
    function();
    return 0;
}
  • A careful look at the program tells us that there is one variable, ‘globalVariable’, defined outside the function. So, as per the definition given above, “globalVariable” has a global scope for the entire program.

Local Scope Variables in C

  • Variables declared within a function or block have local scope. Only accessed within that function or block. These variables cease to exist once the function execution is over.
  • The names of the formal arguments also have local scope.
  • Local scope can be multi-level; there can be an enclosing scope having a nested local scope of an inside block. Another name for local scope is function scope, since the program occurs inside the function

For Example:

C
#include <stdio.h>

void function() {
    int local_variable = 60; // Local variable
    printf("Local variable inside function: %d\n", local_variable);
}

int main() {
    function();
    // printf("Local variable outside function: %d\n", local_Variable); 
    // This will cause an error because local_Variable is not accessible here
    return 0;
}
  • A careful look at the program tells us that there is one variable, ‘local_variable’, defined inside the function. So, as per the definition given above, “local_variable” has local scope in the entire program.

Block Scope Variables in C

  • Variables declared within a block of code (within curly braces{}) have block scope. Hence, they are only accessible within that block and any nested blocks inside it. Once the block is exited, the variables cease to exist.
  • Another name for block scope in C programming is “local scope” or “lexical scope.” These terms are often used interchangeably to refer to the scope of variables declared within a block of code.

For Example:

C
#include <stdio.h>

int main() {
    int x = 40;
    {
        int y = 80; // Block scope variable
        printf("y inside the block: %d\n", y);
    }
    // printf("y outside the block: %d\n", y); 
    // This will cause an error because y is not accessible here
    return 0;
}

A careful look at the program tells us that there is one variable, ‘y’, defined within a block of code (within curly braces {}). So, as per the definition given above, “y” has block scope for the entire program.

Summary

Scope TypeDescriptionParameters
Global ScopeLifetime: Until the function execution is complete.can cause namespace pollution and naming conflicts.
Lifetime: for the duration of the program.
Variables declared within a function but not globally.
Local ScopeVariables declared within a function but not global.Accessible only within the function they are declared in.
Lifetime: Until the block execution is complete.
It helps in encapsulation and avoiding naming conflicts within functions.
Block ScopeVariables declared within a block of code (within curly braces).Accessible only within the block they are declared in; this includes nested blocks.
Cease to exist once the block execution is completed.
Lifetime: Until the block execution completes.
This provides a narrower scope, thereby reducing the risk of naming conflicts.
Summary of all three scopes

For example:

Let us consider the following code to add three numbers:

C
#include <stdio.h>

// Global variable declaration
int globalVariable = 10;

void addNumbers() {
    // Local variable declaration
    int localVariable = 20;

    // Accessing global variable
    printf("Global variable inside function: %d\n", globalVariable);

    // Accessing local variable
    printf("Local variable inside function: %d\n", localVariable);

    <strong>// Adding three numbers
    int sum = globalVariable + localVariable + 30;
    printf("Sum inside function: %d\n", sum);
}

int main() {
    // Block scope variable declaration
    int blockVariable = 30;

    // Accessing global variable
    printf("Global variable in main: %d\n", globalVariable);

    // Accessing block scope variable
    printf("Block scope variable in main: %d\n", blockVariable);

    // Calling function to add numbers
    addNumbers();

    // Accessing global variable
    printf("Global variable in main after function call: %d\n", globalVariable);

    /* Trying to access local and block scope variables from main (will result in compilation error)

   printf("Local variable in main: %d\n", localVariable); 
   Compilation error

   printf("Block scope variable in main: %d\n", blockVariable); 
   <strong>Compilation error</strong> */

    return 0;
}

Explanation of the program:

  • In this program, we have combined all three types of variable scopes:
    1. Global Scope: globalVariable is declared outside of any function and can be accessed from anywhere in the program.
    2. Local Scope: localVariable is declared inside the addNumbers function and can only be accessed within that function.
    3. Block Scope: blockVariable is declared inside the main function block and can only be accessed within that block.
  • Inside the main function, we first access the global and block scope variables and then call the addNumbers function.
  • Inside the addNumbers function, we access the global and local scope variables, and then we perform the addition of three numbers (global, local, and constant 30) and print the results.
  • Finally, we try to access the local and block scope variables from the main function, which results in compilation errors because they are not accessible outside their respective scopes.

This example illustrates the usage and visibility of variables with different scopes in a C program, highlighting their importance in understanding program behavior.

In our next blog post, we will learn more about tokens in C, click here.


Discover more from lounge coder

Subscribe to get the latest posts sent to your email.

Leave a Reply

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

Discover more from lounge coder

Subscribe now to keep reading and get access to the full archive.

Continue reading