In C programming, constant parameters and static variables play a crucial role in managing memory, optimizing performance, and ensuring data integrity. This lecture will cover their usage, benefits, and examples.


1. Constant Parameters

What are Constant Parameters?

A constant parameter prevents accidental modification of a function’s argument inside the function body. It is useful when a function only needs to read a value and should not modify it.

Syntax

void display(const int x) {
    // x = 10; // Error: Cannot modify a constant parameter
    printf("Value: %d\\n", x);
}

int main() {
    int num = 5;
    display(num);
    return 0;
}

Benefits of Constant Parameters

Using const with Pointers

void printArray(const int arr[], int size) {
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
}

int main() {
    int numbers[] = {1, 2, 3, 4, 5};
    printArray(numbers, 5); // The function cannot modify 'numbers'
    return 0;
}

2. Static Variables

What are Static Variables?

A static variable retains its value between function calls. Unlike local variables, which lose their values when a function exits, static variables preserve their state across multiple invocations.

Syntax

void counter() {
    static int count = 0; // Retains value between function calls
    count++;
    printf("Count: %d\\n", count);
}

int main() {
    counter(); // Output: Count: 1
    counter(); // Output: Count: 2
    counter(); // Output: Count: 3
    return 0;
}

Key Properties of Static Variables