int main(int argc, const char *argv[]) {
int n = 42;
int *p = &n;
printf("n = %d\n", n);
printf("*p = %d\n", *p);
if (n == *p) {
printf("n = *p\n");
printf("Therefore n and *p are both of type 'int'.\n");
printf("Therefore we declare them:\n");
printf("int n;\n");
printf("and\n");
printf("int *p;\n");
}
return 0;
}
Name:
Anonymous2011-08-01 23:22
The C syntax is pretty retarded.
You would think it should be int* p. Because you are declaring a pointer to an int. And a pointer to an int can be considered a type. For ex. typedef pint = int* (or something like that, i forget).
But then you also have int *p, *q, *r. Suddenly the * is separated from the int. THIS IS WRONG.
OP here. Thanks for all of your responses. I love how pointless this subject is, and yet every programmer I've meet is usually pretty particular about this, and they have reasons to justify their convention.
I do
int * p;
because it looks like I'm trying to multiply a variable with a type, and it doesn't make any sense, and I like to confuse people whenever possible. And it is also very nice and spaced out. If the asterisk is right next to either word, it all looks too scrunched up for me, and it gives me a headache.
Name:
Anonymous2011-08-02 0:05
typedef void* pointer;
...
...
pointer x = NULL;
I only use void pointers.
Name:
Anonymous2011-08-02 0:07
>>25
Interesting... I could do high-level functions that look nice using this. Thanks for the idea.
If you're programming in C, put the * to right like so:
int *p;
If you're programming in C++, put the * to left like so:
int* p;
If you do anything else, you're doing it wrong.
In C, you tend to think about things more in terms of what it is pointing to. int *p is a pointer to an integer, not so much an integer-pointer.
The reason it makes sense to put the * to left in C++ is largely due to pragmatics, is because the * is a part of type. "p" is an integer-pointer, it's not so much a pointer to an integer.
Furthermore, when you factor in const and volatile qualifiers, placing * to the left becomes more important for nested pointers and references.
int* volatile* const* p;
You now read p's type from right to left. A pointer to a constant pointer to a volatile pointer to an integer.
In C, which traditionally didn't have const, and volatile had slightly different rules, this didn't make so much sense.
>>32
There is no difference in how pointers are defined in C or C++. For both int * is of different type than char *, for example.
C's declarations are designed to mirror the usage and C++ doesn't change anything about that. It's reference system even supports this: int *&p; //p is a reference to a pointer
The reason that C++ doesn't use &int is for compliance with the C standard. There is no reason to suddenly change your mind about this.
It also helps by pairing up the qualifiers with the right asterisks: int *volatile *const *p; //equal to int (*volatile (*const (*p)));