Can We Assign a Integer Value to a Reference Variable?

Can We Assign a Integer Value to a Reference Variable?

It is not possible to assign an integer value to a reference variable directly, say like:

int &x=10; //not possible

Is there any other way we can modify this statement to make it possible?

But not like this:

int a=10;int &x=a;

This works fine. But I want some other way or modify a little bit my expression and make it work!

6

6 Answers

The reference as the name says has to reference to something. How do you want to assign a value to it if it doesn't reference anything?

The reason it doesn't work is because 10 is of the type "const int". You can turn that into a reference, but you can't make it non-const without violating some logic at the least.

const int &a = 10;

that'll work.

int &b = const_cast<int &>(static_cast<const int &>(10));

will also compile, but you can't modify b (as that would imply modifying the actual "10" value).

8

The crux is that 10 is a constant – somewhat obviously: you cannot change its value. But if you try to assign it to an int reference, this would mean that the value were modifiable: an int& is a modifiable value.

To make your statement work, you can use a const reference:

int const& x = 10;

But as “cnicutar” has mentioned in a comment, this is pretty useless; just assign the 10 to a plain int.

You can't bind a reference-to-nonconst to anything immutable.

  • The standard permits storing compile time constants in ROM (btw, attempting to modify const_cast<>ed compile time constants yields undefined behaviour)
  • This would basically strip of the const, even if the const is invisible, therefore subverting the whole const-correctness-thing

However, you can bind a reference-to-const to nearly everything, including temporaries:

Consider this a "feature".

References refer to objects (perhaps temporary objects), not to values. If you want to store a value somewhere, assign it to an object, not to a reference.

As a special case, const int &a = 10; initializes the reference a to refer to a temporary object with the value 10, and it extends the lifetime of that temporary to the end of the scope of a (12.2/5). That's pretty useless with an integer literal, but occasionally useful with objects of class type. Still, this does not assign an integer value to a reference. It creates a temporary, and binds a reference to the temporary.

in the C++0x, you can use int&& (rvalue references ), but this can be used as function parameter.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne
Author

Robert Thorne

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.