Sunday, July 10, 2022

[FIXED] Why a reference to const can refer to a literal?

Issue

Why a "plain" reference can't refer to a literal, and a reference to const can do? As far as I know a literal is not an object!


Solution

You don't want to change the value of 42.

That doesn't mean that the language technically couldn't support lvalue references to literals. After all Fortran did that, as I recall. It just has to create a temporary automatically and pass a reference to that.

But then you can easily get into trouble with code like this:

void advance( int& x ) { ++x; }

void foo()
{
    unsigned i = 7;
    // ...
    advance( i );     // Would advance an automatic temporary's value.
    // Here there would be no change to `i`.
}

Regarding

a literal is not an object!

The literal 42, of simple int type, doesn't denote an object. There's not necessarily a data memory location that holds that value. You can't take its address like &42.

However, as just one example, the literal "Blah" denotes an object: you can take its address, like &"Blah".



Answered By - Cheers and hth. - Alf
Answer Checked By - Mildred Charles (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.