I have 2 versions of my recursive function, one in which I pass by value and other where I pass by reference. Suppose I don't modify the argument in the function, I only read it. So it doesn't matter to me if I pass by value or reference. Which one should I use ? Does passing by reference take the same amount of space in stack as passing by value ..
Example code
passing by reference
void recurse ( int &i) { recurse (i) ; }
passing by value
void recurse ( int i) { recurse (i) ; }
I was expecting that my stack will overflow faster when I pass by value, but I dont get the same observation ..
Usually an int fits in a CPU register, and a reference is a pointer, and a pointer fits in a CPU register. So passing by reference takes the same amount of stack space as passing an int.
This doesn't have to be the case, though. A pointer can be larger or smaller than an int.
I think the rule of thumb is: if the object is small (trivial) and you want to avoid changing its value pass by value because it is a copy of the original (which can't? be altered) otherwise pass by const reference if you don't want the value changed or pass by reference if you subsequently want to change the objects value.