Is there a way to store a static pointer address in an enumeration in C++

Viewed 92

This might not be possible in C++, but I am not sure why. I have been searching stack overflow and google but I'm unable to find an answer.

First I will state the assumptions I'm working off of.

First Assumption: If I have this code at a global scope. I would expect it to be stored in the Data segment of the program which means at compile time the memory address is known. char const* const test1 = "test1";

Second Assumption: Enum values are stored as symbols in the symbol table.

This code compiles:

enum class test : size_t
{
    TEST0 = 123,
    TEST1 = 456
};

However, given that size_t is 32 bits on a 32 bit machine and 64 bits on a 64 bit machine, I should be able to store a pointer's address. However, this will not compile.

char const* const test1 = "test1";

enum class test : size_t
{
    TEST0 = 123,
    TEST1 = (size_t)test1
};

Why does this not work? test1's address should be known at compile time and it should simply be saving the memory address.

The goal of doing this is that I would be able to convert the address back into a pointer and use it to convert my enum into a character array (ie: string).

1 Answers

test1's address is not known at compile time (things like address space layout randomization affect it), and it certainly isn't known while compiling (because variables aren't laid out together in the data segment until linking).

Your question really sounds like an XY problem. If you have a bunch of unique char*s, why stuff them into an enum? They already represent an enumeration.

Related