Passing variables in C++

Just a bit of condensed info that people will hopefully find helpful…

Variables that go ‘in’ but not ‘out’:
==================================

void foo(int x)
{
x=6;
}

-x will not be modified outside the scope of foo
-x is copied (consider overhead for big things)

==================================

void foo(int const &x)
{
x=6; //will no compile
}

-x cannot be modified inside foo
-x is not copied, preventing some overhead

==================================

Variables that go in and out
==================================

void foo(int &x)
{
x=6;
}

-x will be modified within foo and outside of foo
-x is not copied, preventing overhead, but modification of x outside of foo may be undesirable. see the use of const above.
-simpler than using pointer technique and avoids having to change calling code to pass a pointer

==================================

void foo(int *x)
{
*x = 6;
}

-the value at *x will be modified inside and outside foo
-x is not copied
-involves more effort to program

==================================

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s