I came across a Leetcode practice where an input argument to a function is vector<int>& nums
. I normally use C, so I rarely come across this format before. I also just realized that the reference method does not work in C but only in C++ based on testing this code in onlinegdb.com. What are the other differences between how these two functions operate?
Function using pointers:
void FirstModifier(int *a, int *b)
{
/* In the event that a and b are too large to copy to stack,
use pointers (instead of pass by value). Supported in
C and C++. */
(*a)++;
(*b)++;
}
Function using references (from this forum):
void SecondModifier(int& a, int& b)
{
/* If a and b are too large to copy to stack,
use pass by reference (instead of pass by value). Use
const to prevent modifying variables. This method is
only supported in C++, not C. */
a++;
b++;
}
Do they both work the same way? Assuming that a pointer and a reference both consume 4 bytes on a 32-bit machine, do both methods use the same amount of stack as soon as code enters the function? What are some reasons why the second method would be preferred over the first method?
Are the other notable differences in syntax? If I use the first method, I have to call it in this way: FirstModifier(&FirstVar, &SecondVar)
, while the second method can be called with SecondModifier(FirstVar, SecondVar)
. Inside the first function, I would also have to use (*a)
to retrieve contents of the first variable, while in the second function, I can simply use a
to access its value.