-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathreference_parameters.cpp
More file actions
39 lines (24 loc) · 860 Bytes
/
reference_parameters.cpp
File metadata and controls
39 lines (24 loc) · 860 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream> //std::cout
//example function using pointers (C-compatable)
void increaseBy5(int* number);
//example function using reference parameters (C++ only)
void add5(int& number);
int main(){
int x;
std::cout <<"x = ";
std::cin >>x;
std::cout <<"\nx = " <<x;
increaseBy5(&x); // NOTE: we have to use the address-of operator here
std::cout <<"\n x is now = " <<x;
add5(x); // look at how simple this looks...
std::cout <<"\n x is now = " <<x;
}
void increaseBy5(int* number){ //pointers version (backward compatible)
*number += 5;
}
//An Important thing to note is that this won't work with constants.
// (gives errors and doesn't make sense)
// to practice this try replacing `x` in line 20 with a numerical constant. (ie - `6`)
void add5(int& number){ //reference-parameters version (simpler)
number += 5;
}