Tuesday, February 05, 2013

C Programming

Declaration and Definition: subtle differences.

I was reading up on a little difference between words that appear to be the same at first glance. The point to note would perhaps be of interest only to the developer. A declaration is said to have been done when a variable has been told to have a certain data type. A definition is when a variable is given a certain memory to put a value in.

These words came up in my reading of geeksforgeeks.org which had a nice article about the extern keyword. Little surprise that extern is available by default for functions. Also, little surprise that extern is not available by default for variables. Extern primarily means a declaration and no allocation of memory. So, if extern were default then variables would never be given space.

However C declaration of vars with extern with values are not treated as errors.
eg- extern int i=0; 

3 comments:

Unknown said...

umm... I think you might be confusing things here a little bit.

Definition and Declaration are certainly different, at least in the context of C's functions, and have to be understood in a little more detail. As regarding variables, what you seem to be talking about, is the storage class specifiers .

And functions do not get extern by default. Declaration simply tells the compiler to watch out for functions with this signature. when you declare as extern, you are telling that the function will have external linkage. Meaning, if already defined elsewhere, use that definition. If defined here for the first time, then use this definition for all other extern declarations of the same function.

This is my opinion on extern int i=0; not giving errors: you are declaring it as extern, as well as defining it to be 0. so all further references in all linked files where "extern int i;" is used will refer to this i.

Gururaj said...

Wikipedia denies your claim about external functions.

Wiki Extern

and extern var = value is an oxymoron as one would be saying this variable value comes externally and then giving it a value right there.

I do agree that extern on variables are storage class specifiers.

Unknown said...

Yep! I stand corrected, and good to know. extern exists for functions by default.

Also just tried extern var = value; Gcc throws a warning, but it isn't an error. and i can see why. You want to use a global variable defined elsewhere, but maybe as soon as this program is running, you want to change the value? no sorry. i can't see why. :P