
Basics
Calling a function
Like f(1,2), we can use call operator () to call a function, where f is a name and 1,1 is an argument list.
Usage of a function call :
- Initialize the function’s parameters from the corresponding argument
- Transfer control to called function from calling function
Usage of a return statement :
- Return the value in the return
- Transfer control to calling function from called function
Argument and Parameter
Relation:
Arguments are the initiallizer for a function’s parameters.
Key Point:
The order in which arguments are evaluated is not guaranteed.
Local Objects
Local variable
Parameters and variables defined inside a function body.
Automatic objects
- Definition: Objects that exist only while a block is executing.
- Usage: Automatic objects corresponding to local variables are initialized if they has an explicit initializer, otherwise they are default initialized (build-in type is unintialized and object is initialized according to the definition of class).
Local static object
Usage:
If it has no explicit initializer, it is value initialized (build-in type are initialized to zero).
Argument Passing
Passing by Value
Example:
pointer or ordinary type.
Passing by Reference
Usage:
- Allow a function to change the value of one or more of its arguments.
- Avoid copies of objects.
- Return additional information via reference parameter.
Const Parameters and Arguments
Usage:
Top level const on parameters are ignored. We can pass either a const or a nonconst object to a parameter that has a top-level const.
1 |
|
Hence we can’t distinguish between void func(const int i) and void func(int i) which means we can’t define both two functions at the same time.
Key Point:
Use reference to const as possible as we can. Doing so we can forbit function’s caller to change its argument’s value. Moreover, using a reference instead of a reference to const unduly limits the type of arguments that can be used with the function.
1 |
// bad design: the first parameter should be a const string& |
In the case, we can’t call find_char("Hello World", 'o', ctr).
Array Parameter
Key Point:
Array parameter will be converted to a pointer.
Array Reference Parameters
1 |
f(int &arr[10]) // arr is an array of references |
Note :
We need to define the size of the array like above example, so contrary to plain array parameter, it will check the size of array when passing the parameter.




近期评论