Consider the following three ANSI-C programs, and .
Which one of the following statements is true?
View worked solution
Answer: A
To determine which of the programs compile successfully, let us analyze each program's scope and variable declarations:
- Program P1:
Here,int a = 5;is declared as a global variable, andint a = 7;is declared as a local variable insidemain(). In C, a local variable can have the same name as a global variable; the local variable simply shadows the global variable within its scope. This is perfectly valid, so P1 compiles without any error. - Program P2:
Insidemain(), the variableais declared twice (int a = 5;and thenint a = 7;) within the same block scope. Redefining a variable with the same name in the same scope is a compilation error (redefinition/redeclaration error). Thus, P2 fails to compile. - Program P3:
Similar to P2, the variableais declared twice in the same scope, first asintand then asfloat. This is a conflicting type redeclaration error. Thus, P3 fails to compile.
Therefore, only P1 compiles without any error.
Free practice · Your answers on this page are not saved.
