Reputation:
I was reading some info on externs. Now the author started mentioning variable declaration and definition. By declaration he referred to case when: if a variable is declared the space for it is not allocated. Now this brought me to confusion, because I think MOST of the times when I use variables in C, I am actually both defining and declaring them right? i.e.,
int x; // definition + declaration(at least the space gets allocated for it)
I think then that only cases in C when you declare the variable but not define it is when you use:
extern int x; // only declaration, no space allocated
did I get it right?
Upvotes: 26
Views: 21608
Reputation: 1
During declaration, a memory location is reserved by the name of that variable, but during definition memory space is also allocated to that variable.
Upvotes: 0
Reputation: 1
This is how I view it putting together bits and pieces I found on the internet. My view could be askew.
Some basic examples.
int x;
// The type specifer is int
// Declarator x(identifier) defines an object of the type int
// Declares and defines
int x = 9;
// Inatializer = 9 provides the initial value
// Inatializes
C11 standard 6.7 states A definition of an identifier is a declaration for that identifier that:
— for an object, causes storage to be reserved for that object;
— for a function, includes the function body;
int main() // Declares. Main does not have a body and no storage is reserved
int main(){ return 0; }
// Declares and defines. Declarator main defines
// an object of the type int only if the body is included.
The below example
int test(); Will not compile. undefined reference to main
int main(){} Will compile and output memory address.
// int test();
int main(void)
{
// printf("test %p \n", &test); will not compile
printf("main %p \n",&main);
int (*ptr)() = main;
printf("main %p \n",&main);
return 0;
}
extern int a; // Declares only.
extern int main(); //Declares only.
extern int a = 9; // Declares and defines.
extern int main(){}; //Declares and defines. .
Upvotes: 0
Reputation: 145829
Basically, yes you are right.
extern int x; // declares x, without defining it
extern int x = 42; // not frequent, declares AND defines it
int x; // at block scope, declares and defines x
int x = 42; // at file scope, declares and defines x
int x; // at file scope, declares and "tentatively" defines x
As written in C Standard, a declaration specifies the interpretation and attributes of a set of identifiers and a definition for an object, causes storage to be reserved for that object. Also a definition of an identifier is a declaration for that identifier.
Upvotes: 24