[C/C++] Using Reference as function parameter…

Reference is enhanced concept from Pointer in C++.
So, many C++ books says “Reference is better than Pointer. So try to use Reference in possible.”
Yes, reference has big merits. It guarantees that there is enough memory space for the variable. So, we don’t need to do so-called “NULL Check”.
But, in terms of readibility, sometimes, using Pointer is better than Reference. Since C, programmers think that parameter is passed by value. Let’s see below.

func(a); // --- (*1)
func(&a); // --- (*2)

At first look – before looking at declaration of “func()”, programmer tends to think that “Value of ‘a’ is passed. So, even after (*1), value of ‘a’ will be preserved.” and “Address of ‘a’ is passed. So, after (*2), value of ‘a’ may be changed.”
But, Reference stands against of this ‘Normal’ concept. Reference parameter of ‘func()’ may result in changing value of ‘a’. But, in case that ‘func()’ doesn’t change ‘a’, using reference – should be declared as ‘const’ – as parameter can be good choice.

In summary, my recommendation is,

“If possible, use Reference as parameter only when value of parameter is not changed with ‘const’ keyword.”


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 )

Google photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s