Hacker News new | ask | show | jobs
by ericbarrett 2120 days ago
The best argument against this, and for leaving the * by the variable name, is this declaration:

  char* a, b;
Now a has type char * but b is just char. It’s probably not what the author meant and it’s definitely ambiguous even if it was intentional. Better to write:

  char b, *a;
Or, if you meant it this way:

  char *a, *b;
“Well, don’t declare multiple variables on the same line,” you respond. Sure, that’s good advice too. But in mixed, undisciplined, or just old code, it’s an easy trap to fall into.
3 comments

The question is, why doesn't C make

    char* a, b;
apply the char* type to both? (That is, why didn't they design it that way?)

I assume there was some reason originally, but it's made everything a bit more confusing ever since for a lot of people. :/

Edit: Apparently it's so declaration mirrors use. Not a good enough reason IMO. But plenty of languages have warts and bad choices that get brought forth. I'm a Perl dev, so I speak from experience (even if I think it's not nearly as bad as most people make out).

In the olden days of C, pointers were not considered types on their own (you cannot have just a pointer, a pointer must point ‘to’ something, grammatically speaking). The type of the object of that declaration is a char. So it’s not really read as ‘I’m declaring a char-pointer called a’, it’s more along the lines of ‘I’m declaring an unnamed char, which will be accessed when one dereferences a’. Hence the * for dereferencing.
This is why a lot of C people do one definition per line for any non-trivial variables.
I think this is why I abandoned a hobby project. I could not figure out why it crashed!
Another good argument is trying to define a function pointer without typedefs.