Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between extern int a; extern int a=42;

Tags:

c

While I was reading the answers of Use of 'extern' keyword while defining the variable

One of the user answered these way

 extern int a;       //  not a definition 
 extern int a = 42;  //  definition 

I was expecting both are not definitions but declarations. I was thinking Both statements says that the variable is defined outside the function and we have to use extern keyword to use it. is this a mistake by him or is it really a definition ? I know that

extern int a; // variable is already defined but its outside the function
extern int a=42 ; //I guess a variable is assigned a value but not a definition 

but these statement

extern int a = 42; // user said its a definition and now i got  confused

Please clear me with these.

like image 503
niko Avatar asked Sep 30 '11 12:09

niko


People also ask

What is an extern int?

Extern is a keyword in C programming language which is used to declare a global variable that is a variable without any memory assigned to it. It is used to declare variables and functions in header files. Extern can be used access variables across C files.

What is the difference between extern int func (); and int func?

Explanation: extern int fun(); declaration in C is to indicate the existence of a global function and it is defined externally to the current module or in another file. int fun(); declaration in C is to indicate the existence of a function inside the current module or in the same file.

What is extern in C with example?

“extern” keyword is used to extend the visibility of function or variable. By default the functions are visible throughout the program, there is no need to declare or define extern functions. It just increase the redundancy. Variables with “extern” keyword are only declared not defined.

What is extern function in C?

The extern keyword in C and C++ extends the visibility of variables and functions across multiple source files. In the case of functions, the extern keyword is used implicitly. But with variables, you have to use the keyword explicitly.


1 Answers

Whenever initialisation is attempted, the statement becomes a definition, no matter that extern is used. The extern keyword is redundant in such a case because, by default, symbols not marked static already have external linkage.

It doesn't make sense to declare an external variable and set its initial value in the current compilation unit, that's a contradiction.

like image 67
Blagovest Buyukliev Avatar answered Oct 05 '22 16:10

Blagovest Buyukliev