0

The Question

1.)Is it possible to declare a pointer variable to reference to the memory address of a constant??I've tried this before pt = &20;(**pt is a pointer variable) but it's not working , so does it mean we can't do it??By the way if it's possible how am i going to work it out??

3 Answers 3

5

No. You must do this:

const int x = 20;
const int* p = &x;
0

Yes it is.

void * ptr = 0xdeadcode;

Don't do it.

Edit: Or you mean, address of a constant, not constant address? Like:

const int n = 123;
const int *ptr = &n;
0

No, literal constants as 20 are not objects and so they don't have addresses.

Different from that are const qualified variables as in Alex' answer. As all variables they refer to an object and so you may take their address. But beware that you then have to have the pointer also be to the const qualified type.

2
  • Then where the constant 20 is stored during the program execution compare to a variable??Thank you Oct 11, 2011 at 16:06
  • @caramel, it is not stored anywhere in the sense as a variable is. In places where your program uses such a constant, in something like if (x < 20) do_something, the constant is usually directly integrated in the assembler instruction that does the comparison. In some places the compiler might not be able to do so and needs to store it somewhere, but this is completely his internal business and he wouldn't tell you. Oct 11, 2011 at 16:43

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.