1

What is the difference between the following two pointer definitions

int i = 0;
const int *p = &i;
constexpr int *cp = &i;
cmidi
  • 1,590
  • 1
  • 15
  • 31
  • 2
    That one compiles, whilst the other doesn't. (http://ideone.com/NIO41u) – Oliver Charlesworth Feb 09 '15 at 22:18
  • 3
    @OliverCharlesworth You're the one who put it inside a function body, causing the error. That's not in the question. –  Feb 09 '15 at 22:21
  • @hvd: That's a fair point. – Oliver Charlesworth Feb 09 '15 at 22:21
  • It's not a `const` or `constexpr` pointer. It's a pointer to a `const`/`constexpr` `int`. – 0x499602D2 Feb 09 '15 at 22:26
  • `constexpr const int *ccp = &i;` is another possibility – M.M Feb 09 '15 at 22:27
  • 2
    @0x499602D2 according to c++ primer `constexpr *p` is a constant pointer to int and not a pointer to a const int – cmidi Feb 09 '15 at 22:30
  • This has a "to which does the modifier apply, the pointer or the pointee" angle which the proposed duplicate did not. Therefore, it's not a duplicate. – Ben Voigt Feb 09 '15 at 22:35
  • @cmidi Yes, you're right. My mistake. In the duplicate it even says "`constexpr` always refers to the expression being declared (here `NP`), while `const` refers to `int` (it declares a pointer-to-const)" for the declaration `constexpr const int *NP = &N;` – 0x499602D2 Feb 09 '15 at 22:38
  • 1
    Can't a very complete answer be found in this SO question : http://stackoverflow.com/questions/14116003/difference-between-constexpr-and-const – Silverspur Feb 09 '15 at 22:40
  • @BenVoigt The duplicate's answer addresses that point as well (see my above comment). – 0x499602D2 Feb 09 '15 at 22:41
  • @Silverspur there's a lot of info there but it doesn't seem to clearly state things for simple cases (e.g. it doesn't say whether there is any difference between `const int N = 5;` and `constexpr int N = 5;` ) – M.M Feb 09 '15 at 23:49
  • @Matt You're right. Actually, I was just passing by and I remembered the other question. Sorry I did not take time to carefully read this one... – Silverspur Feb 09 '15 at 23:53

1 Answers1

3

const int *p = &i; means:

  • p is non-const: it can be reassigned to point to a different int
  • i cannot be modified through p without use of a cast

constexpr int *cp = &i; means:

  • cp is const: it cannot be reassigned
  • i can be modified through p

In both cases, p is an address constant if and only if i has static storage duration. However, adding constexpr will cause a compilation error if applied to something that is not an address constant.

To put that another way: constexpr int *cp = &i; and int *const cp = &i; are very similar; the only difference is that the first one will fail to compile if cp would not be an address constant.

M.M
  • 130,300
  • 18
  • 171
  • 314