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.

Naveen goud said:   1 decade ago
It's just that when we consider the declaration extern int a:It scopes the value from another file or outside of main() function.

So it takes the int a=20; as a external variable.

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?

Geek said:   1 decade ago
@Sagar, Navin.

I think Navin is wrong. It does not take int a=20 as an external variable. But internal variable a=20 has higher precedence so program uses a=20 value ! :).

I might be wrong though !

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.

Kalyan said:   1 decade ago
But a=20 is declared at outside of main then how it is local?

If it is local we can't declare the same var name a ?

Ganga said:   1 decade ago
#include<stdio.h>
int main()
{
extern int a=40;
printf("%d\n", a);
return 0;
}
int a=20;

Trusti said:   8 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:   8 years ago
a=20 is outside of main(), then how is such output?

Please give me the answer.

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

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


Post your comments here:

Your comments will be displayed after verification.