You cannot get it everywhere! Scopes

In the C programming language, variables have different scopes, which determine their visibility and lifetime within the program. Here are the main types of variable scope in C:

  1. Local Scope (or Block Scope):

    • Local variables are declared within a function or a block and can only be accessed within that function or block.

    • These variables are created when the block is entered and destroyed when the block is exited.

  2. Global Scope:

    • Global variables are declared outside all functions, usually at the top of a C program.

    • They are accessible from any function within the program.

    • Their lifetime is the entire runtime of the program.

  3. Function Scope:

    • This applies to function parameters and function-local variables.

    • They are only accessible within the function where they are declared.

  4. File Scope:

    • Variables with file scope are declared outside of any function, but with the static keyword.

    • They are accessible from any function within the same file (translation unit) but are not accessible from other files.

    • Their lifetime is also the entire runtime of the program, but their visibility is limited to the file in which they are declared.

Understanding these scopes is crucial for managing variable visibility and lifetimes effectively in C programming.

I'll provide a sample program for each type of scope in C and explain how each works.

1. Local Scope (Block Scope)

#include <stdio.h>

void function() {
    int localVariable = 10; // Local variable
    printf("Inside function, localVariable = %d\n", localVariable);
}

int main() {
    function();
    // printf("%d", localVariable); // This line would cause a compile error
    return 0;
}

Explanation:

  • localVariable is declared within the function() and is local to it.

  • It can only be accessed within function().

  • Trying to access it in main() (as shown in the commented line) would cause a compilation error because localVariable is not visible outside function().

Now let's illustrate another block example scope.

#include <stdio.h>

int main() {
    int x = 10; // 'x' has block scope within 'main'

    printf("Outside the block, x = %d\n", x);

    { // Starting a new block
        int y = 20; // 'y' has block scope within this block
        printf("Inside the block, x = %d and y = %d\n", x, y);

        int x = 30; // This 'x' is different from the 'x' outside this block
        printf("Inside the block, new x = %d and y = %d\n", x, y);
    }

    // printf("%d", y); // This would cause an error because 'y' is not accessible here

    printf("Outside the block, x = %d\n", x); // This will print the original 'x'
    return 0;
}

Explanation:

  • x is declared in the main function and is accessible throughout the main function.

  • Within the new block (defined by {}), y is declared. This variable y is only accessible within this block.

  • Inside this block, there is also a new declaration of x. This x shadows the x defined in main and is only accessible within this block.

  • After exiting the block, y is no longer accessible, and attempting to use it will result in a compilation error.

  • Outside the block, the original x from the main function is again accessible, and the x declared inside the block is out of scope.

Block scope in loops is similar to that in any other block of code in C. Variables declared within a loop are only accessible within the loop block.

#include <stdio.h>

int main() {
    for (int i = 0; i < 3; i++) {
        int loopVariable = 100; // 'loopVariable' has block scope within the for loop
        printf("Inside loop iteration %d, loopVariable = %d\n", i, loopVariable);
        loopVariable++;
    }

    // printf("%d", i);          // Error: 'i' is not accessible here
    // printf("%d", loopVariable); // Error: 'loopVariable' is not accessible here

    return 0;
}

Explanation:

  • i and loopVariable are declared within the for loop.

  • i is the loop counter and is only accessible within the for loop.

  • loopVariable is also declared within the loop and is reinitialized to 100 in each iteration. It's only accessible within the loop.

  • Any attempt to access i or loopVariable outside the for loop will result in a compilation error because they are out of scope.

2. Global Scope

#include <stdio.h>

int globalVariable = 20; // Global variable

void function() {
    printf("Inside function, globalVariable = %d\n", globalVariable);
}

int main() {
    printf("In main, globalVariable = %d\n", globalVariable);
    function();
    return 0;
}

Explanation:

  • globalVariable is declared outside of any function, giving it global scope.

  • It can be accessed from any function in the program, including main() and function().

3. Function Scope

#include <stdio.h>

void function(int parameterVariable) {
    int localVariable = 30;
    printf("Inside function, parameterVariable = %d, localVariable = %d\n", parameterVariable, localVariable);
}

int main() {
    function(25);
    // printf("%d", parameterVariable); // This line would cause a compile error
    return 0;
}

Explanation:

  • parameterVariable is a function parameter and has function scope.

  • It is only accessible within function().

  • localVariable is also scoped to function().

  • Attempting to access parameterVariable in main() (as shown in the commented line) would cause a compilation error.

4. File Scope

// File1.c
#include <stdio.h>

static int fileScopedVariable = 40; // File scoped variable

void function() {
    printf("Inside function, fileScopedVariable = %d\n", fileScopedVariable);
}

// Main.c
#include "File1.c"

int main() {
    function();
    // printf("%d", fileScopedVariable); // This line would cause a compile error
    return 0;
}

Explanation:

  • fileScopedVariable is declared with the static keyword outside of any function in File1.c.

  • It has file scope and is only accessible within File1.c.

  • Attempting to access fileScopedVariable from Main.c (as shown in the commented line) would cause a compilation error.

0
Subscribe to my newsletter

Read articles from Jyotiprakash Mishra directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Jyotiprakash Mishra
Jyotiprakash Mishra

I am Jyotiprakash, a deeply driven computer systems engineer, software developer, teacher, and philosopher. With a decade of professional experience, I have contributed to various cutting-edge software products in network security, mobile apps, and healthcare software at renowned companies like Oracle, Yahoo, and Epic. My academic journey has taken me to prestigious institutions such as the University of Wisconsin-Madison and BITS Pilani in India, where I consistently ranked among the top of my class. At my core, I am a computer enthusiast with a profound interest in understanding the intricacies of computer programming. My skills are not limited to application programming in Java; I have also delved deeply into computer hardware, learning about various architectures, low-level assembly programming, Linux kernel implementation, and writing device drivers. The contributions of Linus Torvalds, Ken Thompson, and Dennis Ritchie—who revolutionized the computer industry—inspire me. I believe that real contributions to computer science are made by mastering all levels of abstraction and understanding systems inside out. In addition to my professional pursuits, I am passionate about teaching and sharing knowledge. I have spent two years as a teaching assistant at UW Madison, where I taught complex concepts in operating systems, computer graphics, and data structures to both graduate and undergraduate students. Currently, I am an assistant professor at KIIT, Bhubaneswar, where I continue to teach computer science to undergraduate and graduate students. I am also working on writing a few free books on systems programming, as I believe in freely sharing knowledge to empower others.