I am new to C and I experience some confusion between the declaration and definition of a variable. Another thing I would like to know is if the following is true:
“Declaration appears many times and definition comes once.”
Also:
int x;
Is this a declaration only? Since memory is allocated for x then why isn’t this a definition instead of a declaration?
This isn’t something you see too much in C, but it works like this:
In a header file, you can have a line like this:
Because of the
externmodifier, this tells the compiler that there is an int named x somewhere. The compiler doesn’t allocate space for it – it just addsint xto the list of variables you can use. It’ll only allocate space forxwhen it sees a line like this:You can see that because only the
int x;line changes your executable, you can have as manyextern int x;lines as you feel like. As long as there’s onlyint x;line, everything will work like you want it to – having multiple declarations doesn’t change a thing.A better example comes from C++ (sorry if this is a C-only question – this applies to
structs as well, but I don’t know the syntax off the top of my head):This declaration tells the compiler that there’s a class called “Pineapple”. It doesn’t tell us anything about the class (how big it is, what its members are). We can use pointers to Pineapples now, but we can’t yet have instances – we don’t know what makes up a Pineapple, so we don’t know how much space an instance takes up.
After a definition, we know everything about the class, so we can have instances, too. And like the C example, you can have multiple declarations, but only one definition.
Hope this helps!