Chapter 04 Procedural Abstraction - Function
6. Further Discussion on C++ Functions
6.1 Macro with Parameters
#define <macro-name> (<parameter-list>) <expression>
//example:
#define max(a, b) (((a) > (b)) ? (a) : (b))
Macro is inherited from C and can solves the problem of inefficiency of frequent call to small functions.
The implementing rule for macro with parameters is direct substitution without any checking, which might bring some problems.
6.2 Inline Function
inline <a-function-definition>
Inline function is defined just put the keyword
inline
before the regular function definition. Which has similar function to macro but will check the data type, which is safer than macro.But the keyword
inline
just suggest the compiler to deal with when compiling, whether the suggestion is going to be taken depends on the compiler.And we usually put the definition of inline function in the header file.
6.3 Parameters with Default Value
We can give the parameter a default value when defining or declaring it, but there are some rules to follow:
- Assign default value from right to left;
- A parameter can only be assigned one default value in the same file.
6.4 Function Overloading
In C++, the two function can share the same name if they’ve got some difference in parameters in terms of number of parameters or their data types, which is called function overloading.
6.5 Anonymous Function - Lambda Expression
[<environment-announcement>] (<parameter-list>) -> <return-value-type> <function body>;
//example: call expression include a lambda expression
int n = [] (int x, int y)->int {return x + y;} (3, 4);
About the environment-announcement:
: We can’t use variables in the outer scope;
&
: We can use variables in the outer scope as a quota, which means you can modify them;=
: We can use variables in the outer scope by value, which means you can’t modify them.
More information will be talked later when we discuss passing in a function as an argument.