Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variables to functions

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?

like image 694
Faken Avatar asked Nov 26 '25 21:11

Faken


2 Answers

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:

void foo(int x) {}
void bar(int& x) {}

int i;

foo(i); // copies i, foo works with a copy
bar(i); // aliases i, bar works directly on i

If you mark it as const, you have a read-only alias:

void baz(const int&);

baz(i); // aliases i, baz reads-only i

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.

like image 173
GManNickG Avatar answered Nov 28 '25 10:11

GManNickG


Yes it does.
If you know that you can pass the argument as const& like so:

int function(const string& str) {}

For small types like int or float or char this doesn't worth the hassle since passing a reference is the same as passing an int. doing this makes sense only if you're passing big things like vectors or strings.

The compiler is most likely not going to do this optimization for you because in most cases it can't know that it's allowed to.

like image 20
shoosh Avatar answered Nov 28 '25 11:11

shoosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!