1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

C++ Declarations help

  1. Oct 15, 2006 #1
    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

  2. jcsd
  3. Oct 16, 2006 #2
    Welcome to real programming. Real painful, if nothing else.:uhh:

    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.
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?