osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Tutor] beginning to code


On Fri, Sep 22, 2017 12:03 PM, Dennis Lee Bier <wlfraed at ix.netcom.com> wrote:>
On Fri, 22 Sep 2017 23:30:34 +1000, Steve D'Aprano
>
<steve+python at pearwood.info> declaimed the following:
>

>The exercise is to demonstrate pass by reference semantics. That requires
>
>demonstrating the same semantics as the Pascal swap procedure:
>
>
>
>procedure swap(var a, var b):
>
>  begin
>
>    tmp := a;
>
>    a := b;
>
>    b := tmp;
>
>  end;
>
>
>
>(ignoring the type declarations for brevity).
>
>
>
	Or FORTRAN (since call-by-reference has been the standard in that
>
language from the start -- no special keywords needed to enable reference
>
semantics)... It's been 20 years, and I'm using an F90 text, so this is
>
going to be less than perfect:
>
	subroutine iswap(a, b)
	integer	:: a
>
	integer	:: b
>
	a = IEOR(a, b)
>
	b = IEOR(a, b)
>
	a = IEOR(a, b)
>
	return
>
	end
>
>{That's a bitwise exclusive OR; no temp storage needed}
>
> a = 123
>
> b = 321
>
> a = a ^ b
>
> a
>
314
>
> b = a ^ b
>
> b
>
123
>
> a = a ^ b
>
> a
>
321
>
>
>


And then along comes someone who asks for
to swap array elements a[I] and a[j], where I and j
just happen to be equal.    You don't preserve the
values, as would be anticipated, but instead clear
the argument(s) to zero.

Saving one temp storage is a very tiny gain for the potential cost
of a program malfunction.   And if you go so far as to bring in 
a compiled language like Fortran into the mix, where the
'temp storage' is just a machine register, and not RAM,
you really have saved nothing at all.


I usually do not encourage people to optimize correctness out of their code.