Question:
How does the c keyword "extern" work ?
Andrei
2011-06-26 12:16:45 UTC
I don't fully understand the concept

I've been browsing the web here and there and found something similar to this:
* Let's say you declare a global variable like so:
int iGlobalVar;
* Then you find yourself inside a code-block and wish to access the global variable:
{
// this will apparently link to the globally declared variable
extern int iGlobalVar;
}
* If I declare the latter one without the "extern" keyword, it would temporarily hide the global version of the variable
* Why do I have to use the extern keyword ?
* Why can't I just use the scope resolution operator ?
{
::iGlobalVar; // this would do the same thing right?
}
Hope I didn't annoyed you with these questions
Three answers:
Silent
2011-06-26 12:22:35 UTC
The extern keyword is used to declare a global variable without defining it, telling the compiler that it has already been defined in a different source file.



C does not have a scope resolution operator. C++ does, but you asked about C.
JoelKatz
2011-06-26 12:19:33 UTC
You can use just the scope resolution operator within the same file. But if it's in a different file, how would the compiler know what type the variable was without the extern declaration?
2016-05-14 22:04:58 UTC
When you define a normal variable, such as int b = 0; the variable is defined and initialised at run time. That means that space in memory will be allocated at run time and then given the variable name and initial value. A static variable on the other hand static int a=11; is allocated and initialised at compile time. So when the program is loaded into memory at startup the static variables are already created. Have fun.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...