C Programming - Declarations and Initializations - Discussion

Discussion Forum : Declarations and Initializations - Find Output of Program (Q.No. 3)
3.
What is the output of the program?
#include<stdio.h>
int main()
{
    extern int a;
    printf("%d\n", a);
    return 0;
}
int a=20;
20
0
Garbage Value
Error
Answer: Option
Explanation:

extern int a; indicates that the variable a is defined elsewhere, usually in a separate source code module.

printf("%d\n", a); it prints the value of local variable int a = 20. Because, whenever there is a conflict between local variable and global variable, local variable gets the highest priority. So it prints 20.

Discussion:
31 comments Page 2 of 4.

Manish kulkarni said:   8 years ago
a=20 is outside of main(), then how is such output?

Please give me the answer.

Mahak said:   9 years ago
It is possible because we use an extern keyword for external linkage right.

If we link extern a then it will get the link to global variable int a which is outside that is why answer is 20.

Moreover, we use external linkages for global and non-static variables only.

Raji said:   9 years ago
Here, int a=20; is outside of the main() then how come its possible?

Fahim said:   9 years ago
Here, extern int a is for globally declared functions not for locally declared functions. Here, int a = 20 is declared outside means global therefore it can be accessible by the extern prototype.

Kushal said:   9 years ago
extern int a;

This statement is valid only when the variable is present globally in other file programmer it is local or global variable to same programme and the file in which the variable is declared must be included in the programme otherwise we will get an error.

Ankit said:   1 decade ago
The declaration of the variable is after the variable is used, is that valid? You can declare outside the main function, that's the global variable concept, but in that sequence, do we get that output?

Kokila said:   1 decade ago
a is declared outside the function. How can get the answer 20?

Anitha said:   1 decade ago
For the given question 'a' declared in local variable section so it first search and take the 'a' value first if we don't declare the 'a' value in the program it takes the value 0 because we declare return 0;

Paras said:   1 decade ago
Extern int a;

Above line states that a is an integer variable and extern show that it contain in another files where there is no any integer a, so a=20; is local for this files.

Therefore output of this program is 20.

Jazz said:   1 decade ago
How could we use a=20. It is declared outside the main function.


Post your comments here:

Your comments will be displayed after verification.