Pascal vs C, again (was: Pascals Origins)
Steven Pemberton
steven at mcvax.uucp
Thu Jul 24 23:32:41 AEST 1986
In article <3130 at utcsri.UUCP> greg at utcsri.UUCP (Gregory Smith) writes:
> Given var x: array [1..1000] of integer;
> write a code fragment to find the location of the first 0 in x. The
> condition that no zeroes exist must be distinguished. Further rules:
> - Standard Jensen & Wirth Pascal ( no break from loop )
> - *** x[i] must not be evaluated for i<1 or i>1000 ***
> - The search loop must be terminated as soon as a zero is found.
> - 'a or b', 'a and b' always evaluate both a and b
What I find an elegant solution to this sort of problem is the following:
var state: (searching, found, absent);
i: 1..1000;
i:=1; state:=searching;
repeat
if x[i]=0 then state:=found
else if i=1000 then state:=absent
else i:=succ(i)
until state <> searching;
case state of
found: writeln('found at ', i);
absent:writeln('not there')
end
I like it because it is explicit and generalisable for searches with more
states. Note that i only takes values in 1..1000 and x[i] is only evaluated
once for each element.
I still think Jack Jansen's main point has been ignored in this discussion:
you run a C program that overruns an array, and it may run to completion, or
at best say "Memory fault - core dumped".
Do the same with a Pascal program, and you're quite likely to get something
like "Index out of bounds at line 123, value = -1". (Actually I just tried
it here, and with "x[1234]:=0", I got a compile-time error! The C version
ran without complaint).
This difference can make a huge difference to the time needed to get a
program running, and the confidence you have in it at the end. This
advantage far outweighs the minor notational inconveniences that this group
seems obsessed with.
Disclaimer: I think that there are programming languages FAR better than
both Pascal and C. However, I try to remain objective about all of them.
Steven Pemberton, CWI, Amsterdam; steven at mcvax.uucp
More information about the Comp.lang.c
mailing list