[comp.lang.c] using "=" in a conditional

cla@isis.cs.du.edu (Chuck Anderson) (03/20/91)

You can do a nice string copy with this construct as well:

   (dest is a char array and source is a valid C string)

   while (*dest++ = *source++);

-- 
  *************************************************************************
     Chuck Anderson                uucp    :         uunet!isis!cla 
     Boulder, Co. (303) 494-6278   internet:         cla@isis.cs.du.edu 
  *************************************************************************

torek@elf.ee.lbl.gov (Chris Torek) (03/21/91)

In article <1991Mar20.031419.3677@isis.cs.du.edu>
cla@isis.UUCP (Chuck Anderson) writes:
>You can do a nice string copy with this construct as well:
>   while (*dest++ = *source++);

Of course, you can also write it as:

	while ((*dest++ = *source++) != 0)	/* or != '\0' */
		/* void */;

which will leave no doubt in the reader's mind that you meant `test
the result of copying one element', and not `test one pair of elements'.
Commenting the empty statement (here, with `void', though `do nothing'
or `continue' or `skip' or ... are all fine) will also remove all doubt
as to whether it, too, was unintended.
-- 
In-Real-Life: Chris Torek, Lawrence Berkeley Lab CSE/EE (+1 415 486 5427)
Berkeley, CA		Domain:	torek@ee.lbl.gov

sven@cs.widener.edu (Sven Heinicke) (03/21/91)

In <11195@dog.ee.lbl.gov>, torek@elf.ee.lbl.gov writes:
>In article <1991Mar20.031419.3677@isis.cs.du.edu>
>cla@isis.UUCP (Chuck Anderson) writes:
>>You can do a nice string copy with this construct as well:
>>   while (*dest++ = *source++);

When I read something like this I automaticely think not equal to zero.

>
>Of course, you can also write it as:
>
>	while ((*dest++ = *source++) != 0)	/* or != '\0' */
>		/* void */;
>

And when I am typing c code, rather often my thincking goes much faster then
my typing, especialy with the the five kinds of key boards I normally use (IBM
PC, VT101, VT330, sunwork station and macintosh) and all of those symbols slow
me down.  If I can pal to go through my program ofterwords I sometime put
in the != 0 but only in cases that get rather complicated arguments in c.

-- 
sven@cs.widener.edu                                  Widener CS system manager
Sven Mike Heinicke                                          and Student
(pssmheinicke@cyber.widener.edu (if you must))