Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between const auto & and auto & if object of reference is const

Tags:

// case 1 const int i = 42; const auto &k = i;  // case 2 const int i = 42; auto &k = i; 

Do we need the const keyword before auto in this scenario? After all, a reference (k) to an auto-deduced type will include the top level const of the object (const int i). So I believe k will be a reference to an integer that is constant (const int &k) in both cases.

If that is true, does that mean that const auto &k = i; in case 1 is replaced by the compiler as just const int &k = i; (auto being replaced with int)? Whereas in case 2, auto is replaced with const int?

like image 728
Steve Cho Avatar asked Sep 06 '18 12:09

Steve Cho


People also ask

What does const auto mean?

C++ auto auto, const, and referencesThe auto keyword by itself represents a value type, similar to int or char . It can be modified with the const keyword and the & symbol to represent a const type or a reference type, respectively. These modifiers can be combined.

Can const reference be modified?

But const (int&) is a reference int& that is const , meaning that the reference itself cannot be modified.

Which modifier is used to define compile time constants in Kotlin?

Compile-Time Constants Properties the value of which is known at compile time can be marked as compile time constants using the const modifier.


1 Answers

auto keyword automatically decides the type of the variable at compile time.

In your first case, auto is reduced to int where it's reduced to const int in the second case. So, both of your cases are reduced to the same code as:

const int &k = i; 

However, it's better to have the const explicitly for better readability and to make sure your variable TRULY is const.

like image 127
Praneeth Peiris Avatar answered Sep 19 '22 01:09

Praneeth Peiris