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?
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 .
No. A reference is simply an alias for an existing object.
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).
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.
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.
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