Enhance your grasp of C programming with this quiz focusing on storage classes such as auto, static, extern, and register. Assess your understanding of variable scope, lifetime, and storage duration in C with practical examples and key distinctions.
What is the scope of a variable declared with the 'auto' storage class in a standard C function, as in 'auto int counter;' within a function?
Explanation: An 'auto' variable has block scope, meaning it can only be accessed within the function or block where it is defined. It does not persist beyond that scope, nor is it available globally across files. Variables declared as 'auto' do not last longer than a loop iteration alone, as their scope relates to blocks, not loops specifically. Thus, only block- or function-scoped is correct.
When a static int variable is declared inside a function without explicit initialization, what is its default value?
Explanation: In C, static variables inside functions are automatically initialized to zero if not explicitly set to another value. This differs from auto variables, which would contain an undefined or garbage value if not initialized. The value one or NULL is not assigned by default to static integers.
What is the main purpose of using the 'extern' storage class when declaring a variable like 'extern int sharedValue;'?
Explanation: The 'extern' keyword tells the compiler that the variable’s definition exists elsewhere, often in another file, allowing cross-file variable sharing. It does not store a variable in a CPU register—that relates to the 'register' keyword. ‘Extern’ has no default initialization behavior and does not restrict scope to blocks.
Which of the following is NOT permitted with a variable declared using the 'register' storage class, such as 'register int i;' inside a loop?
Explanation: You cannot take the address of a 'register' variable because it may be stored in a CPU register, not memory. However, using it as a counter, in arithmetic, or initializing it at declaration are all allowed and typical uses. Only the address operation is fundamentally restricted by the register class.
How does declaring a variable as 'static' within a function, such as 'static int visits;', affect its lifetime?
Explanation: A static variable inside a function retains its value between function calls, offering function-level persistence. By contrast, regular (auto) variables are destroyed after each call. Declaring static does not provide wider accessibility outside the function, nor does it prohibit initialization.