// 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
?
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.
But const (int&) is a reference int& that is const , meaning that the reference itself cannot be modified.
Compile-Time Constants Properties the value of which is known at compile time can be marked as compile time constants using the const modifier.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With