Understanding the scope and lifetime of variables is crucial for writing efficient and bug-free C programs. This topic will cover the following key concepts:

  1. Variable Scope

    • Local Scope
    • Global Scope
    • Block Scope
    • Function Scope
  2. Variable Lifetime

    • Automatic (Local) Variables
    • Static Variables
    • Dynamic Variables
  3. Practical Examples

  4. Exercises

Variable Scope

Local Scope

Variables declared inside a function or a block (enclosed in {}) are local to that function or block. They can only be accessed within that function or block.

#include <stdio.h>

void myFunction() {
    int localVar = 10; // localVar is local to myFunction
    printf("localVar inside myFunction: %d\n", localVar);
}

int main() {
    myFunction();
    // printf("localVar in main: %d\n", localVar); // This will cause an error
    return 0;
}

Global Scope

Variables declared outside of all functions are global variables. They can be accessed from any function within the same file.

#include <stdio.h>

int globalVar = 20; // globalVar is global

void myFunction() {
    printf("globalVar inside myFunction: %d\n", globalVar);
}

int main() {
    printf("globalVar in main: %d\n", globalVar);
    myFunction();
    return 0;
}

Block Scope

Variables declared inside a block (e.g., within an if statement or a loop) are only accessible within that block.

#include <stdio.h>

int main() {
    if (1) {
        int blockVar = 30; // blockVar is local to this if block
        printf("blockVar inside if block: %d\n", blockVar);
    }
    // printf("blockVar in main: %d\n", blockVar); // This will cause an error
    return 0;
}

Function Scope

Labels (used with goto statements) have function scope. They can be accessed anywhere within the function.

#include <stdio.h>

int main() {
    goto label;
    printf("This will be skipped.\n");
    
    label:
    printf("This will be printed.\n");
    return 0;
}

Variable Lifetime

Automatic (Local) Variables

These variables are created when the function is called and destroyed when the function exits. They are typically local variables.

#include <stdio.h>

void myFunction() {
    int autoVar = 40; // autoVar is created and destroyed with myFunction
    printf("autoVar inside myFunction: %d\n", autoVar);
}

int main() {
    myFunction();
    return 0;
}

Static Variables

Static variables retain their value between function calls. They are initialized only once and exist for the lifetime of the program.

#include <stdio.h>

void myFunction() {
    static int staticVar = 0; // staticVar retains its value between calls
    staticVar++;
    printf("staticVar: %d\n", staticVar);
}

int main() {
    myFunction();
    myFunction();
    myFunction();
    return 0;
}

Dynamic Variables

Dynamic variables are allocated and deallocated manually using functions like malloc and free. They exist until they are explicitly deallocated.

#include <stdio.h>
#include <stdlib.h>

int main() {
    int *dynamicVar = (int *)malloc(sizeof(int)); // dynamicVar is allocated
    *dynamicVar = 50;
    printf("dynamicVar: %d\n", *dynamicVar);
    free(dynamicVar); // dynamicVar is deallocated
    return 0;
}

Practical Examples

Example 1: Local and Global Scope

#include <stdio.h>

int globalVar = 100;

void myFunction() {
    int localVar = 200;
    printf("Inside myFunction - globalVar: %d, localVar: %d\n", globalVar, localVar);
}

int main() {
    int localVar = 300;
    printf("Inside main - globalVar: %d, localVar: %d\n", globalVar, localVar);
    myFunction();
    return 0;
}

Example 2: Static Variable

#include <stdio.h>

void counter() {
    static int count = 0; // static variable
    count++;
    printf("Count: %d\n", count);
}

int main() {
    counter();
    counter();
    counter();
    return 0;
}

Exercises

Exercise 1: Local and Global Variables

Write a program that demonstrates the use of local and global variables. Create a global variable and modify it inside a function. Print the value of the global variable before and after calling the function.

Solution

#include <stdio.h>

int globalVar = 10;

void modifyGlobalVar() {
    globalVar += 5;
}

int main() {
    printf("Before function call - globalVar: %d\n", globalVar);
    modifyGlobalVar();
    printf("After function call - globalVar: %d\n", globalVar);
    return 0;
}

Exercise 2: Static Variable

Write a function that uses a static variable to count the number of times it has been called. Call this function multiple times from main and print the count each time.

Solution

#include <stdio.h>

void callCounter() {
    static int count = 0;
    count++;
    printf("Function called %d times\n", count);
}

int main() {
    callCounter();
    callCounter();
    callCounter();
    return 0;
}

Conclusion

In this section, we covered the scope and lifetime of variables in C. Understanding these concepts is essential for managing variable visibility and memory efficiently. We explored local, global, block, and function scopes, as well as automatic, static, and dynamic lifetimes. Practical examples and exercises were provided to reinforce the concepts. In the next module, we will delve into recursive functions, building on the knowledge of functions and variable scope.

© Copyright 2024. All rights reserved