int *p, q;
which says "p is a pointer to integer; q is an integer". That's an argument against writing int* p, q;
because that suggests that both p and q are pointers to integer.And yes, you can write (IIRC)
int q, *p;
(See also http://www.stroustrup.com/bs_faq2.html#whitespace) int *p, *q;
typedef int *intp;
intp p, q;
That just screams that the * belongs to the type and not the variable name.At least, that's how I felt until I read your comment. Now at least I understand why using it that way doesn't drive you absolutely insane. So thanks!
Foo* bar(Baz*, Qux*, int, int*, int**);
I myself do it differently depending on the context. In functions I always stick the asterisk to the type, but if I declare variables, I stick it to the name: Foo* bar(Baz* baz) {
Foo *a, b; Baz c, *d;
...
} int *f(void); // "*f()" returns "int" and "f()" returns "int *"
My habit is to always put a space between the type and the asterisk, regardless of whether there is an identifier: sizeof(int *);
x = (char *) y; void (*fn)(int*) // fn takes a pointer-to-an-int and gives you void
Wouldn't this suggest that the type this function takes is `int*`?I've always thought the pointer declaration syntax in C was just an oversight and I get around it's ambitiousness by always declaring variables on their own line.
void (*fn)(int *);Why do you think so?
the 'type' is pointer-to-int, the 'name' is 'p', hence 'int* p'.
I understand pointers quite well, thankyou....
It would be great if the language actually worked that way, because that's the natural way to think about it. Unfortunately, it doesn't. In the simple case of a single pointer variable, we can put the star next to the type and pretend that C works the way we think, but it's a fiction.
It seems to be a perfectly rational reaction to say "oh this was a stupid idea, let's not take advantage of it". (which is honestly a great way to approach a lot of C's features)
edit: In reference to the last line: "oh this was a stupid idea, let's not take advantage of it".
It's a weird feature that generally makes the code more difficult to understand but people still use it a lot, similar to multiple declarations on a single line with pointers mixed in.
In ordinary expressions it is a normal binary operator (just like / or &&), but has the lowest precedence and simply evaluates the left-hand side, discarding the result, then (in that order) evaluates the right-hand side, returning its value as the result.
int* a, *b;
The language was intentionally designed so that the same operators with the same precedence levels are used in declarations as well as in normal expressions.You should only ever declare one thing per line.
int* p;
int q;