Why do some C ++ compilers allow you to take a literal address?

The C ++ compiler, which I will not name, allows you to take the address of the literal, int * p = & 42;

Clearly 42 is an r-value, and most compilers refuse to do this.

Why did the compiler allow this? What could you do with this other than shooting yourself in the foot?

+4
source share
5 answers

What if you need a pointer to an integer with a value of 42? :)

C ++ references are very similar to automatically dereferenced pointers. You can create a permalink to a literal, for example:

const int &x = 42; 

This effectively requires the compiler to initialize a pointer with an integer address with a value of 42, as you could later do this:

 const int *y = &x; 

Combine this with the fact that compilers must have logic in order to distinguish between a value that does not have an accepted address and one that has, so it knows to store it in memory. The first does not have to be a place for memory, because it can be completely temporary and stored in a register, or it can be eliminated by optimization. Accepting the address of a value is potentially an alias; the compiler cannot track and block the optimization. Thus, using the & operator can force a value, regardless of what it is, into memory.

So, you may have discovered an error that combined these two effects.

+5
source

Because 42 is the answer to life, the universe and all that. When asked about his address, this is the answer itself.

+3
source

Tongue slightly (walnut far from completely) on the cheek:

I would say that in a C ++ application code accepting an integer address, the value of lvalue or rvalue is almost always an error. Even using integers to do anything much more than loop control or counting is probably a design error, and if you need to pass an integer to a function that can change it, use the link.

0
source

Found something related to rvalue links in C ++ 0x - displacement semantics http://www.artima.com/cppsource/rvalue.html

0
source

This effectively requires the compiler to initialize a pointer with an integer address with a value of 42

Then why in some compilers we cannot take the literal address directly ?

 int* ptr = &10; 

Link:

 int& ref = 10; 

almost the same as a pointer though ...

0
source

All Articles