Pet Programmer Peeve
I'm currently working on a new blog, and this one will be deprecated at some point in the future. I'll link to the new one when the time comes. However, I felt I had to stop in to point out one of my greatest C/C++ pet peeves.
When a programmer writing a C++ program wants to declare a reference to an integer, he will often write:
int& myInt = i;I am here today to tell you that this practice is wrong and shows that the programmer does not fully understand the C/C++ type system.
Let's start with a simpler situation, declaring a pointer to an integer. This same programmer would no doubt write:
int* myInt = &i;This is no less wrong. The principle behind the syntax of C declarations is that “the syntax is an attempt to make the declaration and the use agree” (K&R, p 122), or more popularly, “declaration mimics use”. This means that, after the type on the left, the declaration expression will look like the variable in use.
To dereference a pointer (get the value to which it points), the programmer writes
*myInt, as in:int j = *myInt;The
* is the dereference operator. It is conceptually the same operator that appears in the declaration of a pointer. It operates on the variable name, not the type. Therefore, the proper declaration is:int *myInt = &i;With the
* attached to the variable. To make the point, it is equally valid to write:int (*myInt) = &i;But it is illegal to write:
(int*) myInt = &i; // Syntax error!While C++ deviates from the “declaration mimics use” ideology, the
& operator for declaring references operates on variable names, just like the * operator. The declaration for a reference is:int &myInt = i;Now, you may say that this is just aesthetics, that this isn't a practical thing to worry about. However, the practice of putting the operator with the type is confusing for new programmers. The programmer from earlier may believe that, to create two references, he can write:
int& myInt = i, myOtherInt = j;This is not a syntax error. Unfortunately, it does not behave as he expects; it declares one reference and one integer because there is no
& operator before the second variable. It is parsed as:int (&myInt) = i, myOtherInt = j;What is worse is that this is a silent error. Because integers and references can be used interchangeably in many places, the novice programmer may not know what is wrong without extensive debugging.
Labels: c, c++, computer science, programming, style



