A quick question:
When i pass a variable to a function, does the program make a copy of that variable to use in the function?
If it does and I knew that the function would only read the variable and never write to it, is it possible to pass a variable to the function without creating a copy of that variable or should I just leave that up to the compiler optimizations to do that automatically for me?
Yes, parameters passed by value are copied. However, you can also pass variables by reference. A reference is an alias, so this makes the parameter an alias to a variable, rather than a copy. For example:
If you mark it as const, you have a read-only alias:
In general, always pass by const-reference. When you need to modify the alias, remove the const. And lastly, when you need a copy, just pass by value.*
* And as a good rule of thumb, fundamental types (int, char*, etc.) and types with
sizeof(T) < sizeof(void*)should be passed by value instead of const-reference, because their size is small enough that copying will be faster than aliasing.