Colin Walls has over thirty years experience in the electronics industry, largely dedicated to embedded software. A frequent presenter at conferences and seminars and author of numerous technical articles and two books on embedded software, Colin is an embedded software technologist with Mentor … More »
C++ reference parameters – the downside
July 18th, 2016 by Colin Walls
Something that I have discovered over the years is a great pleasure. When I am giving information – presenting, teaching, writing an article or a blog – it is not necessarily a one-way process. I often receive useful and interesting information back. I have commented that I learn as much from delivering a class as I might from attending one.
I was recently talking about C++ for embedded at a conference and considering some of the features that I felt resulted in better, clearer and more bug-free code. One of these was the option to pass parameters by reference. Then someone explained a drawback of this feature …
Pointers are a very powerful feature of the C language and largely explain its wide usage for embedded programming. But they can also be confusing and error prone. Of course, C++ has pointers too, but the language offers some opportunities to avoid the use of pointers and, hence, write clearer code. And one of those is the option to pass parameters by reference.
This code might be written in C or C++, for example:
void swap(int *a, int *b)
int temp = *a;
*a = *b;
*b = temp;
The parameters are pointers to data in the calling function and this code is littered with pointer operations, every one of which is a potential error. So, in C++ we can pass the parameters by reference, thus:
void swap(int& a, int& b)
int temp = a;
a = b;
b = temp;
Now, the calling function does not need to provide (explicit) pointers and the pointer operations are eliminated in the swap() function, rendering it more readable and less likely to contain a bug.
This is all fine, but the problem that was pointed out to me was with a call to swap(). In C, the call would look like this:
It is 100% clear that pointers have been passed and, hence, the possibility that the values of x and y might be changed by the call to swap() is quite clear. However, in C++, if reference parameters were used, the call would be written like this:
And there is no clear indication, without resort to the function prototype (which would, of course, be readily on hand if you are using a good IDE), that x and y could get changed.
I guess it is a case of “what you win on the swings, you lose on the roundabouts”.
2 Responses to “C++ reference parameters – the downside”