Summary
In this lesson, you learned that:
- When passing by value, a function gets a copy of the argument. When it changes the copy, the variable of the code that called it stays the same. This is true for vectors too.
- A reference is another name for an existing variable. A parameter with
&after its type (int& score,std::vector<int>& scores) lets the function change the variable or vector you pass to it. The call looks as usual, and the argument must be a variable. - Through references, a function can give back several results at once or swap two variables.
- In the loop
for (int number : numbers),numberis a copy of the element. To change the elements in the loop, writefor (int& number : numbers), or use an index loop. constmeans that the value must not change. A const reference (const std::vector<int>& numbers,const std::string& name) passes a vector or text without copying it, and the function can't change it.- Every variable has an address in memory, which you get with
&x. A pointer (int* p = &x;) holds an address, and with*pyou read and change the variable it points to. - In a declaration,
&and*are part of the type: a reference and a pointer. In an expression,&xis the address of a variable, and*pis the variable the pointer points to. - A function with an
int*parameter is called with an address:addPoint(&score). nullptrmeans that a pointer points nowhere. When a pointer can benullptr, check it before you use it.- Prefer references. Use a pointer when you need "nothing" or to redirect it to another variable.
That covers all the topics of the course. In the next lesson, the final project, you will write one bigger program step by step and use everything you know from the course: variables, conditions, vectors, loops, functions and references.
Instructions
- 1
Let's practice. The vector
scoresholds the results of a test, and the teacher adds a bonus to each one. Write a functionaddBonuswith two parameters: the vectorscores, which the function changes, and the numberbonus. The function adds the bonus to every score, but no score may go over 100 points: anything higher becomes100. Call it with the bonus10before the print loop. The program prints55,82,100,48and76, one per line. - 2
Write a function
findMinMaxthat takes the vector as a const reference and two references toint,lowestandhighest. It stores the lowest and the highest score in them, so it "returns" two values at once. Start by storing the first element of the vector in both. At the end ofmain, create two variables, pass them to the function and print them:Lowest: 48, highest: 100.