Sunday, October 12, 2008

C++ References "syntatic sugar" or not?

When I first learned about references in C++, I dismissed them as "syntactic sugar." That is, they are equivalent to

* const

See the Dan Saks article at http://www.embedded.com/story/OEG20010311S0024 for a good explanation. Lately, though, I've be re-thinking that stance.

I can now see how collapsing the * const into a & might make the code easier to understand. I say "might" because I can also see how it can cause confusion for beginners, since the "&" symbol is also used as the "address-of" operator. However, it does reduce the general confusion caused by pointers in more complex type declarations. such as

const SomeType* const varName

See Marshall Cline's article at http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.5 for an explanation of how to actually read and understand these declarations.

The thing I still don't like about references is that they give no clue whether an object is a stack-based local object or a parameter passed into the method. I can always hope that whoever wrote the method kept it short enough so I don't have to keep scrolling up and down to look at locals and the parameter list. That doesn't, however, always happen. At least some Interactive Development Environments like Visual Studio allow you to hover over a variable to see its type. I haven't used Eclipse in quite a while, so I can't recall whether the various language plug-ins support it. I assume (or at least I hope) that it works for Java.