QUESTION 16 · Scope and Lifetime
Explain local scope, file scope and variable hiding with an example.
5 marksAnswer in brief
Scope determines where a name is visible in the source program. It does not by itself determine how long the associated object exists.
Block scope
A local variable declared in a block can normally be used from its declaration to the end of that block. Nested blocks can use a visible outer name unless an inner declaration hides it. Function parameters in a definition are available within that function body.
File scope
An object declared outside every function has file scope. Its name is visible from its declaration to the end of the translation unit, subject to hiding. A translation unit is roughly a source file after preprocessing, including text brought in from headers. Linkage determines whether declarations can refer to the same entity across translation units.
Example trace
The file-scope value is 10. Inside main, a local value is declared as 20, hiding that file-scope name. A nested block declares another value as 30, which hides the outer local name inside that block. The lines therefore print 20, 30 and 20. The object with value 20 was not changed by declaring the inner object.
Other scopes and good practice
C also has function scope for labels and function-prototype scope for parameter names in prototypes. Use descriptive names and avoid unnecessary hiding, because similar names can confuse readers. A local static object has block scope but lasts throughout execution; this is why scope and lifetime must be studied separately.
C program and output
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int value = 10;
int main(void)
{
int value = 20;
printf("Outer = %d\n", value);
{
int value = 30;
printf("Inner = %d\n", value);
}
printf("Outer again = %d\n", value);
return 0;
}
Sample input and output
This example uses values already written in the program.
Output
Outer = 20
Inner = 30
Outer again = 20
Related exam questions
Related questions in the storage classes category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.
- September/October 2021 · Q1(b) · 8 marks
If a variable has auto storage class by default, why was the auto keyword introduced in C? Explain.
Paper P01 · page 1 - July 2021 · Q2(c) · 5 marks
List and explain storage classes in C.
Paper P04 · page 1
View this category in the exam question bank →