Hello everyone.
I've got question with this part of a code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
usingnamespace std;
int main(){
int n;
cin>>n;
if (n <= 0) break;
int* a = newint [n];
// for (int i=0; i<n; cin >> a[i++]);
for (int i=0; i<n; i++) {
cin >> a[i];
}
for (int i=0; i<n-1; i++) {
int& b = a[i]; } // This line i do not understand
// is b just a copy of array a
}
Does b takes n-1 memory places to remember its values or not?
b is a reference to a[i] as of when it was created.
from there forward when you see b, it is the same as if you has seen a[index] where index = the i used to create it; that is, if b were made from i=3 then b is an 'alias' or identical to a[3].
b is destroyed at the end } so this code makes no sense to me unless its intentionally a short nonsense program to ask the question.
another simpler example:
int x =3;
int &y = x;
y = 11;
cout << x; //what did you get when you tried this in a program?
Does b takes n-1 memory places to remember its values or not?
^^ b uses no memory, actually. The compiler knows the address of a[index] and will substitute that in. If the compiler is unable to resolve it at compile time, b will turn into a pointer in assembly language.