void VoidRef (int &ref){
ref++;
}
void VoidPtr (int *ptr){
(*ptr)++;
}
int test= 5;
VoidRef(test);
cout << test; // is 6
VoidPtr(&test);
cout << test; // is 7 !
Why do both voids do the same thing? Which void needs more resources?
void VoidRef (int &ref){
ref++;
}
void VoidPtr (int *ptr){
(*ptr)++;
}
int test= 5;
VoidRef(test);
cout << test; // is 6
VoidPtr(&test);
cout << test; // is 7 !
Why do both voids do the same thing? Which void needs more resources?
void VoidRef (int &ref){
//^^pass by reference
ref++;
}
void VoidPtr (int *ptr){
//^^ptr stores address of test
(*ptr)++;
}
Why do both voids do the same thing?
ref
is a reference to test, i.e., an alias of test
, so operation on ref
is also operated on test
.
ptr
is a pointer that stores the memory address of test
, so (*ptr)++
will increment the value that stored on the memory address by one. The reason that the first output is 6 and the second output is 7 since each call to those two functions increments the variable value by 1.
You can think of
both VoidRef
and VoidPtr
operates on the address of the variable test
, therefore, they have same effect.