Hacker News new | past | comments | ask | show | jobs | submit login

What's the common way of doing this in C? Is it normally something like this?:

  firsttime=True
  while (True) {
  ..
  ..
  ..
  firsttime=False
  }



Depends on the person. There likely is a correlation on what century you learned programming, but certainly one whether you have experience with pascal-ish languages.

People educated in the Wirth way would say "that's not a for loop; there is no way to tell how often it will iterate when it is first entered" and write it as a while loop.

Old-school C programmers seem to think one iteration construct is enough for everybody and like to write any iteration as a for loop, ideally with a few commas and no actual statements, as in the classic strcpy:

  char *strcpy(char *dst, CONST char *src)
  {
    char *save = dst; 
    for (; (*dst = *src) != '\0'; ++src, ++dst);
    return save;
  }
(from http://www.ethernut.de/api/strcpy_8c_source.html)

Programmers with soe Wirth-style training do at least something like

  char *
  strcpy(char *s1, const char *s2)
  {
    char *s = s1;
    while ((*s++ = *s2++) != 0)
	;
    return (s1);
  }
(from http://www.opensource.apple.com/source/Libc/Libc-167/gen.sub...)

[If you google, you can find way more variations on this. for example, http://fossies.org/dox/glibc-2.20/string_2strcpy_8c_source.h... does a do {...} while(....) that I am not even sure is legal C; it uses offsets into the source to write into the destination]

From your example I guess you are definitely in the Wirth (Pascalish) camp, beyond even that second state. Classic C programmers would either use 0 and 1 for booleans or #define macros FALSE and TRUE (modern C has true booleans, but that extra #include to get it increases compilation time, so why do it?

I am in te Pascal-ish camp. I like to say C doesn't have a for loop because its 'for' is just syntactic sugar for a while loop.


I find the for loop easier to read.


That's probably the cleaner way to do it, but honestly, the hacked for-loop feels pretty clean too. And it ensures that your firsttime flag is properly set, regardless of how you break out of the loop (a 'continue' in the middle of your example would fail to set the flag properly).




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: