[fpc-pascal] converting c code

Dimitri Smits smitco at telenet.be
Sun May 13 16:06:43 CEST 2012



----- Oorspronkelijk e-mail -----
> On Sun, 13 May 2012 15:09:15 +0200
> Darius Blaszyk <dhkblaszyk at zeelandnet.nl> wrote:
> 
> > I'm struggling to convert a simple for loop from C to pascal. The
> > code is shown below (as is a trace of the loop parameter values).
> > I'm a bit puzzled how this should look elegantly in pascal. Anyone
> > has an idea?
> 
> IMHO the C code is short, but not elegant. It would be more elegant
> if
> the j=i is at the end.
> 
>  
> > unsigned nc = 4;
> > 
> > for (unsigned i = 0, j = nc-1; i < nc; j=i++)
> > {
> > 	cout << "i:" << i << endl;
> > 	cout << "j:" << j << endl;
> > }
> > 

> Maybe:
> 
> var i,j: integer;
> begin
>   j:=nc-1;
>   for i:=0 to nc-1 do begin
>     writeln('i:',i);
>     writeln('j:',j);
>     j:=i;
>   end;


actualy, Marco's version is more correct. A C(++) for loop does it's evaluation on the fly, whereas in pascal (or some dialects), the for variable(s) are immutable or evaluated as early as possible. In this case it might work, but in general, a C++ for loop is better written as a pascal's "while ... do" of "repeat ... until" construct because of this.

consider a loop where you want to exit out of when a condition is met. In C(++) you can change the values of the for loop's variables on the fly et voila, on next iteration you return.

at least, that was what we were told in our CS courses, comparing C(++) vs Pascal/Modula/Oberon (almost 2 decades ago).

kind regards,
Dimitri Smits



More information about the fpc-pascal mailing list