& 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 parameterint &num
. This means thatnum
is an alias for the argument passed to the function, allowing the function to modify the original value.Function Call:
In the
main
function, theincrement
function is called withvalue
as the argument. Since theincrement
function takes an integer reference, any changes made tonum
inside the function will directly affect thevalue
variable in themain
function.Output:
- After calling the
increment
function, the value ofvalue
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.