How not to write a loop

Michael I. Bushnell mike at turing.UNM.EDU
Mon Feb 29 02:35:08 AEST 1988


In article <296 at draken.nada.kth.se> d86-ctg at nada.kth.se (Claes Thornberg) writes:
>A simple recommendation for all hackers(?) writing programs. Even
>though your program is 'running' on the machine you are using now,
>please think a little about compatibility. When giving away programs,
>which I encourage you all to do, there may be a lot of machine
>dependent bugs not doing this, and it is frustrating trying to locate
>these in a program you haven't written yourself, especially when you
>know the program worked when you got it. And thinking of simple things
>like not using real variables in for-loops isn't that hard, I think I
>was told not to do this in my very first programming class. So all you
>hackers using obscure features that works on only a few machines,
>please spare us the time it takes to locate bugs that shouldn't exist.


>From K&R I find:

	The for statement

		for (expr1 ; expr2 ; expr3)
			statement

	is equivalent to

		expr1;
		while (expr2) {
			statement
			expr3;
		}

A difference in the semantics of continue is mentioned.

I see NOTHING which precludes:

	float x;
	for (x = 0; x < 20; x += .5)
		printf("%f\n", x);

The output would, of course, be

	0.0
	0.5
	1.0
	.
	.
	.
	19.0
	19.5

In fact, the "loop" variable can be anything whatsoever, not
even a variable at all!

Try
	for (open_socket(); connection_waiting(); accept())
		process_data();

as a main loop for a server which want to die when no one wants it 
anymore.

C has no notion of "for variables" at all, really.  But maybe the
condescending poster didn't mean loop control variables.  Maybe he
meant just what he says: "using real variables in for loops".  I 
guess he just doesn't want to see:

	int x;
	float f;
	for (x = 0; x < 10; ++x) {
		scanf("%f\n", f);
		printf("%f\n", f);	
	}
as a weird way of echoing floats.

Sigh.



				Michael I. Bushnell
				Internet: mike at turing.unm.edu
				UUCP: mike at turing.unm.edu
				Bitnet: mike at turing.unm.edu
				CSnet: mike at turing.unm.edu
				YourFavoriteNet: mike at turing.unm.edu
			Golly, don't domains make everything simpler?
For peoply who run UUCP but haven't switched over to smail *yet*, you
can try {ucbvax,gatech}!unmvax!turing!mike.  

Or write:
  {Box 295, Coronado Hall} or {Computer Science, Farris Engineering Center}
  University of New Mexico
  Albuquerque, NM 87131
Or call:
  (505)277- [2992=dorm][6116=work]

I work for the CS department.  But don't blame them.



More information about the Comp.lang.c mailing list