Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why reference const can be re-assigned in for-statement?

Tags:

c++

I'm new to C++, and I'm confused about this:

vector<int> v = { 1,2 }; const int &r1 = v[0]; //r1 = v[1];  // compiler will show error. 

I understand that reference const r1 cannot be re-assigned. But look at the codes below:

for (const int &r2 : v) cout << r2; 

Why wouldn't that go wrong? The reference const r2 is assigned twice, right?

like image 422
Xun Chenlong Avatar asked Oct 23 '15 07:10

Xun Chenlong


People also ask

Can you copy a const reference?

Not just a copy; it is also a const copy. So you cannot modify it, invoke any non-const members from it, or pass it as a non-const parameter to any function. If you want a modifiable copy, lose the const decl on protos .

Can a const reference refer to a non const object?

No. A reference is simply an alias for an existing object.

Can const variable be changed?

Constants are block-scoped, much like variables declared using the let keyword. The value of a constant can't be changed through reassignment (i.e. by using the assignment operator), and it can't be redeclared (i.e. through a variable declaration).

What const means?

Const (constant) in programming is a keyword that defines a variable or pointer as unchangeable. A const may be applied in an object declaration to indicate that the object, unlike a standard variable, does not change. Such fixed values for objects are often termed literals.


1 Answers

No it's not assigned twice. r2 exists from the start of the iteration (a single round over the loop body) until the end of the iteration. r2 in the next iteration is another object by the same name. Each iteration has their own r2 and each of them is initialized separately.

like image 79
eerorika Avatar answered Sep 23 '22 21:09

eerorika