Declaring Functions


 
 
 The prototype above yields the following information to the compiler:
  • func is the function name
  • the function is called with two arguments: the first argument is of type int, the second of type double
  • the return value of the function is of type long.

Mathematical standard functions

Declarations

Each name (identifier) occurring in a program must be known to the compiler or it will cause an error message. That means any names apart from keywords must be declared, i.e. introduced to the compiler, before they are used.
Each time a variable or a function is defined it is also declared. But conversely, not every declaration needs to be a definition. If you need to use a function that has already been introduced in a library, you must declare the function but you do not need to redefine it.

Declaring Functions

A function has a name and a type, much like a variable. The function's type is defined by its return value, that is, the value the function passes back to the program. In addition, the type of arguments required by a function is important. When a function is declared, the compiler must therefore be provided with information on
  • the name and type of the function and
  • the type of each argument.
This is also referred to as the function prototype.
Examples:
intnt toupper(int);
double pow(double, double); 
This informs the compiler that the function toupper() is of type int, i.e. its return value is of type int, and it expects an argument of type int. The second function pow() is of type double and two arguments of type double must be passed to the function when it is called. The types of the arguments may be followed by names, however, the names are viewed as a comment only.
Examples:
int toupper(int c);
double pow(double base, double exponent); 
From the compiler's point of view, these prototypes are equivalent to the prototypes in the previous example. Both junctions are standard junctions.
Standard function prototypes do not need to be declared, nor should they be, as they have already been declared in standard header files. If the header file is included in the program's source code by means of the #include directive, the function can be used immediately.
Example:
#include <cmath> 
Following this directive, the mathematical standard functions, such as sin(), cos(), and pow(), are available. Additional details on header files can be found later in this chapter.

 

Post a Comment

0 Comments