For some time now, it’s bothered me that a lot of people are being taught to write
int* a;
rather than
int *a;
The problem, as any experienced C programmer should be able to tell you, comes when you write
int* a, b;
Unfortunately, the interpretation implied by the spacing is that a and b are both pointers to integers. This is not, however, the case; instead, a is a pointer to an int
, whilst b is an int
.
The way the compiler reads this declaration mirrors the way that C programmers tend to write these kinds of statements:
int *a, b;
where it is obvious from the spacing that *
a is an int
(which implies that a is a pointer to an int
) and b is an int
.
The point is that the green part is the type, whilst the things you are declaring are the blue parts. The type of the resulting variable a is certainly pointer-to-int
, but the declaration to the C compiler does not say that, it just says that *
a is an int
, and to get the type of a, you have to read outwards from the variable name. This way of reading declarations works for all C and C++ declarations. The other way does not, forcing people to treat declarations like “int* a
” as a special case.
Writing things in such a way that a human being will read them differently to the compiler is just plain wrong. You can’t (as Bjarne Stroustrup tries to) justify it by saying that people shouldn’t write multiple variable declarations on a line—the C syntax (like that of C++) is perfectly clear and very easy to understand, provided you don’t try to space it as if it was e.g. Pascal.
It’s particularly telling that you can (if you like) write declarations using additional parentheses, like this:
int (*a); int b, (*c), d;
though you can’t write
(int*) a;
(Well, not as a declaration, anyway…)
Of course, this syntax isn’t normally used by macho parenthesis-hating C programmers :-)
Anyway, consider this a plea, particularly to teachers of C and C++ programming: Please don’t teach your students to write ‘int* a
’. It isn’t how the compiler reads it, and you will only make things more confusing for them.
Finally, for those people who like a puzzle, here’s an interesting declaration to decipher:
int (*(*fn)(const char *n))(int a, int b);
and you can award yourself extra brownie points for knowing—without using typedef
or any pre-processor macros—how to write a function definition, a pointer to which could be assigned to a variable like the one above.
(Hint: think where you’re supposed to start reading the declaration to work out the type of fn.)