1

What is the difference between the following two pointer definitions

int i = 0;
const int *p = &i;
constexpr int *cp = &i;
asked Feb 9, 2015 at 22:16
12
  • 2
    That one compiles, whilst the other doesn't. (ideone.com/NIO41u) Commented Feb 9, 2015 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. Commented Feb 9, 2015 at 22:21
  • @hvd: That's a fair point. Commented Feb 9, 2015 at 22:21
  • 2
    @0x499602D2 according to c++ primer constexpr *p is a constant pointer to int and not a pointer to a const int Commented Feb 9, 2015 at 22:30
  • 1
    Can't a very complete answer be found in this SO question : stackoverflow.com/questions/14116003/… Commented Feb 9, 2015 at 22:40

1 Answer 1

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.

answered Feb 9, 2015 at 23:56
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.