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 1 of 4.

Rossy said:   3 years ago
#include<stdio.h>
int main()
{
extern int i;
i = 20;
printf("%d\n", sizeof(i));
return 0;
}

For this code the solution was a linker error then why isn't it an error for this question? Anyone, Please explain.

Mukta said:   5 years ago
a=20 is outside of main(), then how is such output? Please anyone explain me.
(1)

Acecrocdile said:   6 years ago
In the program;

extern int a;( a is "declared" inside the main program not "defined", therefore its scope becomes local to the main program).

int a=20; (here the definition of 'a' occurs where a is being defined to a value of 20 and that has no concern with the scope of 'a' cuz scope of 'a' already gets local on declaration).
(1)

Krishu said:   6 years ago
HERE, ----> int i=20; (is a Global variable but its scope lies inside the program i.e it is local to the program in which it is defined).

AND, -----> extern int i; ( it is pointing to variable 'i' in other program/location i.e global to the program).

Thus the program will use the variable that is local to the program even though if it is defined globally in the program.
(1)

Mukthahar said:   6 years ago
Please explain the output of this.

Shailesh said:   6 years ago
What will be its sequence of execution?

Shreeshail Karajol said:   7 years ago
Because they used an extern variable. It's like a global variable.

Trusti said:   7 years ago
var a is outside the braces then how it would be print 20 in output bcos the printf statement is into braces?

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

Please give me the answer.

Mahak said:   7 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.


Post your comments here:

Your comments will be displayed after verification.