Sunday, August 23, 2009

Function declaration and definition

A function definition includes the program code of the function entirely. For example, the definition of printMultiples:

void printMultiples( int multiplier )
    cout << "| " << multiplier << " |";

    int multiplicant = 1;
    while( multiplicant <= 9 )
        cout << setw(3) << multiplier*multiplicant;

    cout << " |" << endl;

A function declaration specifies the characteristics:
  • The name of the function
  • The number of parameters
  • The type of each paramete
  • The return type of the function

Declaration has the form:
return_type Function_name(formal_parameters);

For example:
void printMultiples( int multiplier );

A function declaration is also called the function prototype. The declaration has all the information about the function the compiler needs in order to be able to check whether the function call in the code is legal, i.e. is semanctically correct.

The definition has all the information of the declaration, but it also included the body of the function. In practice:
  • A function must always be defined (only once) somewhere in the program code
  • A function must always be either declared or defined before it is called of the first time so that the compiler can check the code for errors
  • A function cannot be defined within another function definition

Previous post

Next post

No comments:

Post a Comment