PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, July 10, 2022

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

 July 10, 2022     c++, reference     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing