Date: Wed, 26 Jan 2022 21:03:01 +0000
On , 2022Jan26, at 14:26, Alexey Kreshchuk <akrsch_at_gmail.com<mailto:akrsch_at_[hidden]>> wrote:
for (auto &elem : array)
elem = elem * 9;
After that I tell them that & does not create a new variable but a new name for an old variable.
Agree with describing a reference as “a new name”. I usually call it an alias. (And I stress how it is not a pointer, for the students that have learned C)
But you can give a better treatment of this example if you first introduce references by them selves.
Regular loop
for ( int a : array ) { stuff } === for ( “every element of the array” ) { int a = “that element” ; stuff }
With ref:
for ( int &a : array ) { stuff } === for ( “every element of the array” ) { int &a = “that element” ; stuff }
Pass by value:
Void f( int a ) { stuff } int main() { int x; f(x); } == f() { int a = “the x from the calling site”; stuff }
Pass by reference:
Void f( int &a ) { stuff } int main() { int x; f(x); } == f() { int &a = “the x from the calling site”; stuff }
Your “create a new name for an old variable” is completely outside of the language. You're hoping that they can create a mental picture of what your words mean. By couching it in terms of references you’re losing some of the black magic. You’d be explaining it in terms of language mechanisms they have already seen and hopefully understood.
Victor.
Received on 2022-01-26 21:03:05