Sunday, September 4, 2011

Definition and Declaration in C and C++

Definition vs Declaration in the C and C++ codes:

Definition means where a variable or function is defined in reality and actual memory is allocated for variable or function. Declaration means just giving a reference of a variable and function. Through declaration we assure to the complier that this variable or function has been defined somewhere else in the program and will be provided at the time of linking. In the above examples char *func(void) has been put at the top which is a declaration of this function where as this function has been defined below to main() function.

There is one more very important use for 'static'. Consider this bit of code.

char *func(void);
void main()
char *cpTempResult;
cTempResult = func();

char *func(void)
char caTempResult [10]="martin";

Now, 'func' returns a pointer to the memory location where ' caTempResult' starts BUT caTempResult has a storage class of 'auto' and will disappear when we exit the function and could be overwritten but something else. The answer is to specify

static char caTempResult [10]="martin";

The storage assigned to 'caTempResult' will remain reserved for the duration if the program.

No comments:

Post a Comment