Question:
A very dumb C++ question? Can a pointer hold its own memory address?
Hahir H
2010-04-29 10:43:46 UTC
Yes I know this is dumb and I'll never need to do that but curiosity is curiosity?
would this work?:
void * p=&p;
Three answers:
?
2010-04-29 11:14:02 UTC
It's not dumb. Pointers are a difficult topic in C++, since they are used in several different ways.



Here, "void* p" declares p to be a pointer to an object of any non-const type. And since "void *" is itself a non-const type, p can certainly point to an object of type "void *", such as itself.



And of course, the object to point to should already exist (or, as the Standard says in 8.5/2, the initializer must be an "expression involving literals and previously declared variables and functions"), so

void* p;

p = &p;

as Samwise wrote.



To see what I mean by "non-const", and to see that C++ does make certain checks, despite what some people think, try

const int i = 1;

void * p = &i; // this won't compile

It also won't allow void* to point to a volatile int, come to think of it.
Samwise
2010-04-29 10:50:16 UTC
You could certainly write

void * p;

p=&p;



The problem with writing it as the one-line

void * p=&p;

is that the compiler might object on the grounds that &p is not defined until the statement defining p is compiled. This might vary from compiler to compiler, so code that uses might work in a specific case but not be portable.



At any rate, the two-step method is entirely valid, if you ever do find a use for it.
2010-04-29 10:45:30 UTC
Sure, C/C++ doesn't care what the pointer is actually pointing to. There are no checks.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...