& before function arg in cpp

Adding the Ampersand (&) Before Function Arguments in C++

#include <iostream>
using namespace std;

void increment(int &num) {
    num++;
}

int main() {
    int value = 5;
    increment(value);
    cout << "Incremented value: " << value << endl;
    return 0;
}

Explanation:

  • Function Definition:
  • The increment function is defined with an integer reference parameter int &num. This means that num is an alias for the argument passed to the function, allowing the function to modify the original value.

  • Function Call:

  • In the main function, the increment function is called with value as the argument. Since the increment function takes an integer reference, any changes made to num inside the function will directly affect the value variable in the main function.

  • Output:

  • After calling the increment function, the value of value is printed, showing the effect of modifying the original value through the reference parameter.

The ampersand (&) before the function argument in C++ indicates that the argument is passed by reference, allowing the function to modify the original value.