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.
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.
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;
}
const with Pointersvoid 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;
}
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.
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;
}