C++: Function Definition


A function is a body of code that returns a value. The value returned may depend on arguments provided to the function.

Write a definition of a function called “multiply” that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are created and values returned).

C++ functions basically are the same as in C. Also macros exist, however they are discouraged in C++ in favour of inline functions and function templates.

An inline function differs from the normal function by the keyword inline and the fact that it has to be included in every translation unit which uses it (i.e. it normally is written directly in the header). It allows the compiler to eliminate the function without having the disadvantages of macros (like unintended double evaluation and not respecting scope), because the substitution doesn’t happen at source level, but during compilation. An inline version of the above function is:

inline double multiply(double a, double b)
	return a*b;

If not only doubles, but numbers of arbitrary types are to be multiplied, a function template can be used:

template<typename Number>
Number multiply(Number a, Number b)
	return a*b;

Of course, both inline and template may be combined (the inline then has to follow the template), but since templates have to be in the header anyway (while the standard allows them to be compiled separately using the keyword export, almost no compiler implements that), the compiler usually can inline the template even without the keyword.


Content is available under GNU Free Documentation License 1.2.