2009年7月30日 星期四

What is the declarations and definition ?

A declaration is a source code construct that associates attributes with names. A declaration either introduces a name into the current translation unit or redeclares a name introduced by a declaration that appeared earlier in the same translation unit.

Among the attributes that a name may have are its type, scope, storage duration, and linkage. Not every name has all of these attributes. For example, a function name has a type, a scope, and a linkage, but no storage duration. A statement label name has only a scope.


A declaration might also be a definition, which provides not just some of the attributes of a name, but rather all the information the compiler needs to create the code for that name.

For functions and objects, a definition is a declaration that generates storage. It's easy to tell when a function declaration is also a definition--a function definition has a body, which generates storage in the code space. For objects, the distinction is not so simple--it depends on the object's scope, linkage, and initializer.

For C:

1. function

int func(); //declaration
int func(){

return 0;

}

2. object

// this is in global area
int i;
// tentative definition.(在C++中是不合法的)
// this becomes declaration after seeing the next definition ("int i;"是一個宣告式, "int i=0;"是一個定義式)
int i=0;

For C++:


1. function (the same as C)

int func(); //declaration
int func(){

return 0;

}

2.object
在C++僅有使用extern且沒有做 initialize就是宣告式

int i; // definition, assign 0 to i
static int j; // definition
extern int k = 0; // definition
extern int m; // non-defining declaration

沒有留言: