All Exams Test series for 1 year @ ₹349 only
Question

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

P1P2P3
#include <stdio.h>

int a=5;
int main(){
int a=7;
return(0);
}
#include <stdio.h>

int main(){
int a=5;
int a=7;
return(0);
}
#include <stdio.h>

int main(){
int a=5;
float a=7;
return(0);
}


Which one of the following statements is true?

The correct answer is
Only P1 will compile without any error

C Program Compilation Analysis

This question asks to identify which of the three given C programs (P1, P2, P3) will compile successfully without errors. We need to analyze the variable declarations and scope rules in each program.

Program P1 Compilation

Program P1:

$#include <stdio.h>
int a=5; // Global variable 'a'
int main(){
    int a=7; // Local variable 'a'
    return(0);
}
$
  • P1 declares a global variable $a$ and a local variable $a$ inside $main$.
  • In C, having a local variable with the same name as a global variable is allowed. The local variable $a$ shadows the global variable $a$ within the scope of the $main$ function.
  • Therefore, P1 will compile without any errors.

Program P2 Compilation

Program P2:

$#include <stdio.h>
int main(){
    int a=5;
    int a=7; // Error: Redefinition of 'a'
    return(0);
}
$
  • P2 attempts to declare an integer variable $a$ twice within the same scope (the $main$ function).
  • Redeclaring a variable within the same scope is illegal in C.
  • Therefore, P2 will result in a compilation error (redefinition of variable 'a').

Program P3 Compilation

Program P3:

$#include <stdio.h>
int main(){
    int a=5;
    float a=7; // Error: Redefinition of 'a'
    return(0);
}
$
  • P3 attempts to declare two variables named $a$ within the same scope (the $main$ function), one of type $int$ and the other of type $float$.
  • Even though the types are different, declaring two variables with the same name in the same scope is not allowed.
  • Therefore, P3 will result in a compilation error (redefinition of variable 'a').

Conclusion

Based on the analysis:

  • P1 compiles successfully.
  • P2 fails due to redeclaration of $a$.
  • P3 fails due to redeclaration of $a$.

Thus, only P1 will compile without any error.

Was this answer helpful?

Important Questions from Programming in C

  1. Which among the following is a valid string function?

  2. A function which calls itself is called a

  3. Which of the following function sets first n characters of a string to a given character?

  4. Which of the following statement provides an easy way to dispatch execution to different parts of code based on the value of the expression?

  5. Which of the following operators has left to right associativity?

Need Expert Advice?

Start Your Preparation with Prepp Mobile App

Download the app from Google Play & App Store
Download the app from Google Play & App Store
Prepp Mobile App