Thursday, December 24, 2009

Funny "C"- Weird Pointers

You have a declaration:

int* ptr_a, ptr_b;

Given this, what is the type of ptr_b? int *, right?

Wrong!

C’s declaration syntax ignores the pointer asterisks when carrying a type over to multiple declarations. If you split the declaration of ptr_a and ptr_b into multiple statements, you get this:

int *ptr_a;
int ptr_b;

It’s possible to do the single-line declaration in a clear way. This is the immediate improvement:

int *ptr_a, ptr_b;

Notice that the asterisk has moved. It is now right next to the word ptr_a. A subtle implication of association.

Finally, I should point out that you can do this just fine:

int *ptr_a, *ptr_b;

No comments:

Post a Comment