Functions

A function declaration establishes the name and the parameters of the function.

 

                                                            /-------------\
                                                                         |
>>----------------------------------function_declarator--(------------------->
    |-extern-|  \-type_specifier-/                           \-parameter-/
    \-static-/
>--)----------------><
      |-const----|
      \-volatile-/

The use of the const and volatile specifiers is only supported by C++.

A function is declared implicitly by its appearance in an expression if it has not been defined or declared previously; the implicit declaration is equivalent to a declaration of extern int func_name(). The default return type of a function is int.

To indicate that the function does not return a value, declare it with a return type of void.

A function cannot be declared as returning a data object having a volatile or const type but it can return a pointer to a volatile or const object. Also, a function cannot return a value that has a type of array or function.

If the called function returns a value that has a type other than int, you must declare the function before the function call. Even if a called function returns a type int, explicitly declaring the function prior to its call is good programming practice.

Some declarations do not have parameter lists; the declarations simply specify the types of parameters and the return values, such as in the following example:

int func(int,long);

 

In C, you cannot declare a function as a struct or union member.

 

Default Arguments in C++ Functions

In C++, you can provide default values for function arguments. All default argument names of a function are bound when the function is declared. All functions have their types checked at declaration , and are evaluated at each point of call.

For example :

/**
 ** This example illustrates default function arguments
 **/

#include <iostream.h>
int a = 1;
int f(int a) {return a;}
int g(int x = f(a)) {return f(a);}

int h()
{
     a=2;
     {
            int a = 3;
            return g();
     }
}

main()
{
     cout << h() << endl;
}