C++ Logo

sg20

Advanced search

Re: Introducing references

From: Alexey Kreshchuk <akrsch_at_[hidden]>
Date: Wed, 26 Jan 2022 23:26:24 +0300
I teach my students (who already know python) references with a range-based
for loop. It goes something like this:

// you can use a loop similar to `for elem in array:`
for (auto elem : array)
    std::cout << elem << "\n";
// But what if you want to modify the element? In python you switch to
indices and range(len(array))
// But in C++ you can have some magic
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. Then show the trivial example in the context of "we
can also use & here but we don't need to". And only later do I introduce
functions.
I think this approach is better for students that already have some
experience with range-based for loop as it solves the problem that they
have most certainly already encountered.


ср, 26 янв. 2022 г. в 23:03, Victor Eijkhout via SG20 <sg20_at_[hidden]
>:

>
>
> On , 2022Jan26, at 13:33, Arthur O'Dwyer <arthur.j.odwyer_at_[hidden]>
> wrote:
>
> FWIW, I teach
> - pass-by-value
> - problems: performance of all those copies; how to write an out-parameter?
> - C solution: pointers (a pointer holds a memory address)
> - pass-by-pointer
> - C++ enhancement: references (***)
> - pass-by-reference
>
>
> I agree with your sequence, and I use something very similar.
>
> But…..
>
> Why do you teach the “pass by pointer”? Maybe you and I have different
> audiences. I have 1 semester to get engineering undergrads writing (from
> scratch) semi-serious simulations in clear, working, not-too-inefficient
> code. So I teach the C stuff way at the end of the semester as “In case
> someone throws you an old code base, you may come across this.” Otherwise I
> see no reason for teaching it.
>
> Otherwise thanks for agreeing (or at least sympathizing) with me.
>
> Victor.
>
> --
> SG20 mailing list
> SG20_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/sg20
>

Received on 2022-01-26 20:26:38