lectures.alex.balgavy.eu

Lecture notes from university.
git clone git://git.alex.balgavy.eu/lectures.alex.balgavy.eu.git
Log | Files | Refs | Submodules

Functions.md (1616B)


      1 +++
      2 title = 'Functions'
      3 +++
      4 # Functions
      5 defined by types of input parameters, its name, type of return value, and algorithm that computes return value from input values
      6 
      7 example:
      8 
      9 ```cpp
     10 int add(int a, int b) {
     11   return a+b;
     12 }
     13 ```
     14 
     15 when a function is called, thread of execution continues within code of function
     16 
     17 as soon as it returns, code that called the function continues
     18 a function returns if:
     19 1. It reaches a return statement
     20 2. It reaches the end of its code block
     21 
     22 a void function is allowed to reach end of its code block
     23 
     24 a function that has a return value must reach a return statement or throw an exception
     25 
     26 ## Parameters
     27 parameters in declaration of function are called *formal parameters*
     28 parameters in call of function are called *actual parameters*
     29 
     30 Rules of thumb:
     31 1. Use pass-by-value for small objects
     32 2. Use pass-by-const-reference for large objects that you don’t need to modify
     33 3. Return a result rather than modifying parameter through reference
     34 4. Use pass-by-reference only when you have to — when there’s no alternative
     35 
     36 pass-by-value:
     37 
     38 - copies actual parameters into formal parameters
     39 - formal parameters in function can’t modify anything outside the function
     40 - happens by default
     41 - inefficient with large parameters
     42 - `void print(vector<double> v) {}`
     43 
     44 pass-by-const-reference
     45 
     46 - passes address of values (reference)
     47 - efficient, no copying of data
     48 - safe, parameter is const and can’t be overwritten
     49 - `void print(const vector<double>& v) {}`
     50 
     51 pass-by-reference
     52 
     53 - if we want to modify contents of parameters, pass by reference
     54 - `void init(vector<double>& v) { v[2]=2; }`