To explore and demonstrate different pointer operations in C++ through call by value and call by reference methods.
Software Used: MinGW Compiler, Visual Studio Code, and Online C++ Compilers.
In this approach, copies of the variables are passed to the function. Inside the swap()
function, the values appear to interchange, but these modifications only apply to the local copies, leaving the original a
and b
unchanged in main()
. This technique highlights that call by value never changes the actual data in the calling function—it only modifies duplicates inside the function.
- Start
- Define a function
swap(x, y)
- Save
x
in a temporary variableaa
- Assign
y
tox
- Assign
aa
toy
- Print the swapped values inside the function
- In
main()
, callswap(a, b)
- Print the original values of
a
andb
- Stop
Here, instead of passing variable copies, we provide the addresses of variables to the function. Using pointers (*x
, *y
), the function directly accesses and updates the original variables. Therefore, after execution, both a
and b
actually get swapped in main()
. Unlike the previous method, this ensures changes are permanent outside the function, making it useful for real data modification.
- Start
- Define a function
swap(int *x, int *y)
- Store the value of
*x
in a temporary variableaa
- Assign
*y
to*x
- Assign
aa
to*y
- Print swapped results inside the function
- In
main()
, callswap(&a, &b)
- Print updated values of
a
andb
- Stop
This method uses C++ reference variables so that the function directly works on the original variable without explicitly using pointers. A reference parameter int &x
points to the actual memory of variable a
. When x
is increased by 45 inside the function, a
itself gets updated. This process is simpler than pointer syntax yet provides the same direct modification facility.
- Start
- Define a function
swap(int &x)
- Declare a constant value
aa = 45
- Increment
x
byaa
- Print the updated value inside the function
- In
main()
, seta = 3
- Print the original value of
a
- Call
swap(a)
- Stop
These three programs illustrate different ways of passing arguments to functions in C++:
- Call by value → passes copies, so the original variables remain unchanged.
- Call by reference using pointers → passes addresses, allowing real changes to original variables.
- Call by reference using references → a cleaner syntax that directly modifies the original data without dealing with pointer operators.
Altogether, these examples show that the choice of parameter passing method depends on whether the original data should remain untouched or be updated by the function.