The difference between const int & value = 12 and const int value = 12;

Possible duplicate:
Can const reference be assigned int?

Is there any subtle difference between

const int& value = 12; 

and

 const int value = 12; 

when compiling? How?

+4
source share
3 answers
 int value = 12; 

Here 'value' is a value variable.

where int & is used to create a reference variable (alias) for another variable. how

 int i; int& j=i; 

j and i refer to the same memory location. it c++ concept.

But a reference variable cannot be created for a memory location. Therefore, in my idea, the following expression is a promt error

 int& i = 12; `Will not compile even.` 

About const:

The const keyword is used to create a read-only variable. After initialization, the value of the variable cannot be changed. consider the following code:

 const int x = 2; // const var can be initialized, not modified thereafter x = 10; // error - cannot modify const variable 

Error: Error: Read-only variable assignment 'x'

Also, the expression can use const on both sides of the type.

  const int value = 12; int const value = 12; 

Both expressions are the same (for simple data types other than pointers). learn from here The most common places we see are function arguments or return values.

const with reference variable :

A temporary one is created and it is legal to bind a const link to it, but illegal to bind a const to it.

It's simple:

 const int& reference_to_const_int = int(20); //LEGAL int& reference_to_const_int = int(20); //ILLEGAL 

A const link extends the life of the temporary, so this works. This is just a language rule. (I learned from here )

+1
source

The first is the reference constant assigned by the number, and the second is the lvalue constant assigned by the number. There is no difference in terms of use, because none of them can be changed by the user of the "value".
The compiler, obviously, treats the link differently in that the link is usually an alias of some object of the type declared by it, in which case the link number without a variable name is assigned to the link.

0
source

See explanation of this question .

So you can write code like this:

 void f( const string & s ) { } ( "foobar" ); 

and etc.

Looks like I got an offer for such an incomplete answer. But this question is essentially a duplicate of the one I am associated with.

There is more detailed information to describe what the difference is in this matter.

-1
source

Source: https://habr.com/ru/post/1439040/


All Articles