Machine-translated by Google. Questions are authored in English.
Top

Discussion

Consider the following three ANSI-C programs, P1, P2, and P3.

P1P2P3
#include \(\lt\)stdio.h\(\gt\)
int a=5;
int main(){
 int a=7;
 return(0);
}
#include \(\lt\)stdio.h\(\gt\)
int main(){
 int a=5;
 int a=7;
 return(0);
}
#include \(\lt\)stdio.h\(\gt\)
int main(){
 int a=5;
 float a=7;
 return(0);
}

Which one of the following statements is true?

  • A.Only P1 will compile without any error
  • B.Only P2 will compile without any error
  • C.Only P3 will compile without any error
  • D.All three programs P1, P2, and P3 will compile without any error

Answer: A

Only P1 will compile without any error.

P1 declares a global int a=5; and a local int a=7; inside main. These are in different scopes, so the local declaration simply hides the global one inside main. That is legal C.

P2 declares int a twice in the same block scope. C does not allow two definitions of the same identifier in one block, so this is a redeclaration error.

P3 declares a as an int and then as a float in the same block: a conflicting-types error. So only P1 compiles, which rules out the other three options.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.