What Do These C++ Declarations Mean?

  • Context: C/C++ 
  • Thread starter Thread starter peejake
  • Start date Start date
  • Tags Tags
    C++
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
1 reply · 3K views
peejake
Messages
69
Reaction score
0
Hey guys,

I need a little more help here with this C++ stuff. Can anyone give me some help on how to give the meaning of these declarations:

1) const int a;
2) int const a;
3) const int *a;
4) int *const a;
5) int const * a const;

Any help would be appreciated as i am new to c++ and i am still in the learning stage

Thanks
jake:smile:
 
Physics news on Phys.org
Welcome to real programming. Real painful, if nothing else.:rolleyes:

1 & 2 are the same. I prefer 2 on purely aesthetic grounds.

3,4,5: To read pointer declarations, work right to left.

3: "a is a pointer to (const) int" the pointee is const--it can't be changed through the pointer. The pointer can be changed; it can be pointed at a new pointee. I prefer to declare as: "int const * a", it better supports the right->left reading.

4: "a is a const pointer to int"--the pointer can't be changed--i.e. it can only point to the pointee it was initialized with; pointee can be changed via the pointer. This declaration always raises the question, would you prefer a reference in this situation? Not always (sometimes you really want an address, as in hardware programming, etc), but often a reference helps you avoid bad pointer madness that runs rampant in C.

5: "a is a const pointer to a const int"--neither pointer nor pointee can change. Akin to a const reference.

Good luck.