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.
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.
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.
“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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With