Santhosh Pai Santhosh Pai - 1 year ago 113
C Question

Extern inside function

I know this is an basic question , not sure the c standard allows it to do or not .I was given a code snippet in an interview and was asked to give the output.

I have declared an extern and an local variable with the same name inside a function it throws a re declaration error ( just like global) what could be the reason ? since i is declared in the same block, extern should be able to find it rite ?

#include <stdio.h>

int main(void){

int i = 10;
extern int i ;

printf("%d \n",i);


Error : 1.c: In function ‘main’:
1.c:13: error: extern declaration of ‘i’ follows declaration with no linkage
1.c:12: note: previous definition of ‘i’ was here

Answer Source
int i = 10;
extern int i ;

The first, because it is function scope, means "declare and define a variable i which is local to the function". The variable shall have no linkage because it is function local.

The second says "declare a variable i which has external linkage".

It is allowed, within certain limitations, to re-declare a variable, but in general the declarations must be consistent; the two statements above contradict. Furthermore, an identifier with no linkage cannot be re-declared - from C11 6.7 paragraph 3:

If an identifier has no linkage, there shall be no more than one declaration of the identifier (in a declarator or type specifier) with the same scope and in the same name space

(after which some exceptions are listed, but they are not relevant here).

If the statements were outside the function (at file scope level) then the int i = 10; declaration would indicate external linkage, so the following declaration is consistent. Function locals however do not have linkage.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download