function

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 :

  1. Initialize the function’s parameters from the corresponding argument
  2. Transfer control to called function from calling function

Usage of a return statement :

  1. Return the value in the return
  2. 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

  1. Definition: Objects that exist only while a block is executing.
  2. 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:

  1. Allow a function to change the value of one or more of its arguments.
  2. Avoid copies of objects.
  3. 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
2

void (const int i){// func ca nread but not write to i}

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
2
// bad design: the first parameter should be a const string&
string::size_type find_char(string &s, char c, string::size_type &occurs);

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
2
f(int &arr[10])     // arr is an array of references 
f(int (&arr)[10]) // arr is a reference to an array

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.