Hi @ACTISA,
You said that if you use void increment(int number) instead of void increment(int &number) works the same way. This information is almost true because there is a subtle thing happening that changes everything, which is:
-
When you use pointers or references, the value is changed in the original variable inside the main function. When you don’t use pointers/references, the value is changed locally.
-
Now, imagine you have a huge video to edit. Would you want to have a copy of the variable, which would consume a lot of memory, or would you like to modify the video in the original variable, saving resources, and not having to return the modified video?
Taking your code as an example, here I have a modified version of it:
#include <iostream>
using namespace std;
void incrementByReference(int &number) {
cout << "\nref:: The address of number is: " << &number << endl;
number++;
cout << "ref:: Now the value of number is: " << number << endl;
}
void incrementByPointer(int *number) {
cout << "\npointer:: The address of number is: " << number << endl;
(*number)++;
cout << "pointer:: Now the value of number is: " << *number << endl;
}
void incrementByValue(int number) {
cout << "\nvalue:: The address of number is: " << &number << endl;
number++;
cout << "value:: Now the value of number is: " << number << endl;
}
int main() {
// Declare the number
int number = 42;
// Print the number's value
cout << "The initial value of number is: " << number << " and the address is: " << &number << endl;
// Call the function incrementByReference
// This will change the value in the main function
incrementByReference(number);
// Calling incrementByPointer will also change the value in the main function
incrementByPointer(&number);
// incrementByValue changes the value only insde the incrementByValue function itself.
// The value on the main function keeps untouched
incrementByValue(number);
cout<<"\n main::Now the value of 'number' at 'main' function: " << number <<endl;
return 0;
}
If you compile this code and execute it, you will see something similar to the following:
The initial value of number is: 42 and the address is: 0x7ffe4738fe84
ref:: The address of number is: 0x7ffe4738fe84
ref:: Now the value of number is: 43
pointer:: The address of number is: 0x7ffe4738fe84
pointer:: Now the value of number is: 44
value:: The address of number is: 0x7ffe4738fe6c
value:: Now the value of number is: 45
main::Now the value of 'number' at 'main' function: 44
Please analyze the modified code I posted, and the output until you really understand it. Understanding this will definitely make your life easier.
How much better to get wisdom than gold,
to get insight rather than silver!
- Proverbs 16:16