I understand the basic difference between the passing by value and passing by reference. Passing by value means that you pass values as function arguments and passing by reference means that you just simply pass the variable.
What I don't get is how exactly works. Here is my example.
#include <iostream>
// Initializing Functions
void swap(int &first, int &second);
void write_and_prompt();
int main()
{
int num1 {30};
int num2 {185};
std::cout << "The original value of num1 is: " << num1 << '\n';
std::cout << "The original value of num2 is: " << num2 << '\n';
std::cout << "\nSwapping values..." << '\n';
std::cout << "Values have been swapped." << '\n';
// Function for swapping values.
swap(num1, num2);
std::cout << "\nThe value of num1 is: " << num1 << '\n';
std::cout << "The value of num2 is: " << num2 << '\n';
// Function that ends program after users input
write_and_prompt();
} // End of main
// Creating Fucntions
void swap(int &first, int &second)
{
int temp = first;
first = second;
second = temp;
}
void write_and_prompt()
{
std::cout << "\nPress enter to exit the program." << '\n';
std::cin.get();
}
So what I don't understand is when I call the function swap(num1, num2) I'm passing these two variables but in the syntax of the function I have &first, &second.
I thought that I was passing the address of num1 and num2 but then I thought that I would need pointers in the function to be able to work with them plus I would use the address-of operator in front of num1 and num2 instead.
Anyway what I trying to understand is why using the address-of operator(&) makes the function take the variables num1 and num2.
I thought that this operator just gives the address of the variable or maybe I didn't understand it correctly.