0

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.

TryingCpp
  • 5
  • 3

2 Answers2

0

int & is a reference to int and is different from address-of operator. Your function parameters are references so you don't need to pass address or pointers.

Omid
  • 286
  • 1
  • 5
  • 20
0

You are correct that the unary & operator gives the address of a variable. However, & in function arguments is not the address-of operator--it's marking that particular parameter as being pass-by-reference, which has different semantics than passing around pointers. If you want to pass in pointers, you'd use int *first, int *second, same as declaring a pointer-to-an-integer within a function body.

Putnam
  • 704
  • 4
  • 14
  • Yeah and If I used int *first, int *second in my swap function I would need to have &num1, &num2. But I didn't know that the operator & isn't exactly the address-of operator when I use it on a parameter of a function. Thank you very much! – TryingCpp Jun 06 '20 at 11:40