pass by value vs. by reference


// example
#include <iostream>

// Pass by reference
void scale_number(int &num); // Prototype

// function definition - pass by reference
void scale_number(int &num) {
    if (num > 100)
    num = 100;
}

void print_numbers2(int num) {
    cout << "Printing int: " << num << endl;
} 
int main() {

// pass by reference
int number_scale = 1000;
scale_number(number_scale); // call function
cout << number_scale << endl;   // 100

   return 0;
}



// example 2
void swap (int &a, int &b);

int main() {

int x = 10, y = 10;
cout << y << " " << y << endl; // 10 20
swap(x, y);
cout << x << " " << endl; // 20 10

return 0;
}

void swap(int &a, int &b) {
		int temp = a;
		a = b;
		b = temp;
}

// example 3
// PASS BY VALUE
void print(std::vecotr<int> v); // prototype

int main() {
		std::vector<int> data = {1, 2, 3, 4, 5};
		print(data);
return 0;
}

void print(std::vector<int> v) { // Declaration
		for (auto num: v)
		cout << num << endl;
}

// PASS BY REFERENCE
void print(std::vecotr<int> &v); // prototype

int main() {
		std::vector<int> data = {1, 2, 3, 4, 5};
		print(data);
return 0;
}

void print(std::vector<int> &v) { // Declaration
		for (auto num: v)
		cout << num << endl;
}
// not possible to reinizialize the reference value

perfomance increase since the variable will not be copied because the original reference variable will be redifined