Lesson 19: Functions, return types, pass by value / reference

[spoiler title=”Lesson Video”]
Direct Download of Video (For mobile / offline viewing)(right click > save target as)


[/spoiler]

[spoiler title=”Lesson Source Code”]

#include 
using namespace std;

int addFive(int);
int addFiveRef(int&);
void addFiveToAll(int[]);

int main(){
  int x = 0;
        //Homework
  //Using an array of strings for days of the week and an array for days (your choice on type) in the months of the year, ( 31, 28,...) 
  //Figure out the last day of a user input month for the year 2015, or 2016.
  //2016, July etc.

  /*cout << addFive(x) << endl; // What will this line output?
  addFive(x); //5 that floats and does nothing
  cout << x << endl; // What will this line output?

  cout << "Reference: " << endl;
  cout << addFiveRef(x) << endl; // What will this line output?
  addFiveRef(x);
  cout << x << endl; // What will this line output?*/

  int myArray[5] = { 1, 3, 5, 7, 9 };
  addFiveToAll(myArray);

  for (int i = 0; i < 5; i++){
    cout << myArray[i] << endl;
  }

  system("pause");
  return 0;
}

int addFive(int y){
  y += 5;
  return y ;
}

int addFiveRef(int &y){
  y += 5;
  return y;
}

void addFiveToAll(int anArray[]){
  for (int i = 0; i < 5; i++){
    anArray[i] += 5;
  }
}

[/spoiler]

Homework: Using an array of strings for days of the week and an array for days (your choice on type) in the months of the year, ( 31, 28,…) Figure out the last day of a user input month for the year 2015, or 2016. Ex: 2015, July.



What is passing by reference?
Passing by reference is when you pass an argument into a function directly. The default way which you pass arguments into a function is called “Pass by value” in which a perfect copy of the variable you are passing is made, and the one you passed is not affected by any actions taken within the function. Pass by reference passes the variable itself into the function (via reference, which we will touch on later), and any alterations made to that variable throughout the course of the function are passed made directly to the variable itself and thus persist outside of the function even without assignment.

The only difference in syntax between passing by reference and passing by value is an ampersand (&) which is put before the variable name in the function’s argument list.

int addFive(int &myNumber){} // pass by reference
int addFive(int myNumber){} //pass by value