translating a C for loop to Pascal

Viewed 74

I am translating an "old" C program into (Object) Pascal. I am reconsidering my translation of the following:

for (objlist = list->unbounded; objlist; objlist = objlist->next) {
  /* do stuff */
}

At first I translated the loop as follows:

objlist := list.unbounded;
repeat
  // do stuff
  objlist := objlist.next;
until objlist = nil;

But then I wondered, what happens if "objList" is nil? Should the loop be translated as a while loop (so objList can be tested before entering the loop)?

objlist := list.unbounded;
while (objlist <> nil) do
  begin
    // do stuff
    objlist := objlist.next;
  end;

Thanks in advance.

2 Answers

It is a while loop for sure. C for-loop is actually a while-loop

You should always strive to writing robust code, code which works even when the premises changes and a pointer suddenly could become null. It is good practice to check a pointer for null before using it.

Even thou it looks like the c code is a repeat... until The c for loop actually checks for null on the first iteration.

You could try this with a simple example

#include <stdio.h>
  
int main(){
  for(int i=20 ;i < 10;i++){
      printf("%d\n",i);
   }
   return 0;

}

see this flow diagram C loop for diagram from https://beginnersbook.com/2014/01/c-for-loop/

And even if the original code did not check for an initial null pointer I would recommend the second while loop style.

Related