Today's Question:  What does your personal desk look like?        GIVE A SHOUT

C/C++ Pointer Declaration Syntax – It makes sense!

  Erlend        2012-02-22 05:43:58       2,761        0    

I never really liked the way pointers are declared in C/C++:

int *a, *b, *c; // a, b and c are pointers to int

The reason is that I am used to reading variable declarations as MyType myVar1, myVar2, myVar3; and I always read “int*” as the type “integer pointer”. I therefore wanted the following

int* a, b, c; // a is a pointer to int, b and c are ints

to mean that a, b and c all were of type int*, i.e. pointers to int. and I therefore found it slightly annoying to repeat the asterisk for every variable. This also meant that the symbol * had two slightly different meanings to me: (1) It declares a pointer or (2) it dereferences a pointer.

I usually don’t declare a whole lot of pointers in one line, but still, this is a (minor) annoyance I have briefly discussed with few fellow programmers over the years.

Today I started reading C Traps and Pitfalls by Andrew Koenig and after reading one sentence, in chapter two, the pointer declaration syntax suddenly makes – at least some â€“ sense:

[…] Analogously,

float *pf;

means that *pf is a float and therefore that pf is a pointer to a float.

Of course! If I instead of looking at it as a variable a of type int*, we read it as *a – i.e. “a dereferenced” – it makes sense. That is indeed an int, and that also means that * always means “dereference”.

Source:http://hamberg.no/erlend/2012/02/21/cc-pointer-declaration-syntax-it-makes-sense/

C  POINTER  DECLARATION  ATTEMPT 

Share on Facebook  Share on Twitter  Share on Weibo  Share on Reddit 

  RELATED


  0 COMMENT


No comment for this article.