From the perspective of the compiled program, is there any difference between these two:
1 2 3 4 5 6 7 8
int return_val (int& input) { // doesn't create anything on the stack
return input;
}
int main() {
int input = 5;
int output = return_val(input);
}
and this:
1 2 3 4 5 6 7
int return_val (int input) { // creates a new variable "input" on the stack
return input;
}
int main() {
int output = return_val(5);
}
My understanding is that these two are identical, as in the later case a variable with the value "5" will be declared within the function anyway, so the former case is preferable (for me) as it would force me to pass a variable by reference if possible, reducing the likelihood of me causing the compiler to declare a variable twice, as in this unfortunate situation:
1 2 3 4 5 6 7 8
int return_val (int input) { // input added to stack
return input;
}
int main() {
int input = 5; // added to stack again...
int output = return_val(input);
}
I realise this looks like microoptimisation but I have some low-level loops that are really chewing into my wall-time and I wanted to save as much as I can. I was thinking of making all my function pass by reference, as this would be at least the same and at best reduce unnecessary declarations. Is that true?
Pass by reference can be used to avoid copying big/expensive objects. If that is the only reason you pass by reference pass a const reference instead and you will not have the problem with having to create a temp variable to pass things as argument.
Passing small objects like an int by reference to a function will not do much good. It can even make it slower. If the compiler can inline the function call there will probably be no difference in this case.
So when passing ints and floats, is it best just to pass them without reference, or by const&? Does it make any difference at all?
Also, what is the diference between passing as const& or just passing as reference? I'm assuming the former means the function can't modify the variables, but how is it different from a performance perspective?
Yes, it is a compile-time only feature that gives C++ some amount of const-correctness. That doesn't mean it isn't possible to change the variable through some frowned-upon pointer casting, though. :p