Assignment in test: OK?

Jeremy Fitzhardinge jeremy at sinope.socs.uts.edu.au
Wed Sep 12 12:30:22 AEST 1990


george at hls0.hls.oz (George Turczynski) writes:

>In article <BURLEY.90Sep6024459 at world.std.com>, burley at world.std.com (James C Burley) writes:
>> Your code is fine IMHO.  But suppose you had written the following
>> accidentally:
>> 
>>     if (foo = 0)
>> 
>> This is a common mistake.

My friendly local compiler would say "Constant conditional branch" to this -
a useful warning.  Annoyingly this also pops up with "while(1)" (but not
"for(;;)"). Of course this doesn't help with "if (i = TestThing())", however
this is quite a useful construct.  How many would prefer
	if (thing != NULL)
	{
		fp = fopen(thing, "r");
		if (fp == NULL)
			barf();
	}
to
	if (thing && (fp = fopen(thing, "r"))
		barf();
?

>This is only a mistake if you don't know what you're doing (or you have a
>typo, in which case it's only a mistake for a short while).  It is, in fact,
>perfectly legal C, but isn't what people sometimes want it to mean.
>
>> ...... is just trying to get you to look at ifs containing assignments, just
>> in case you meant to say "if (foo == 0)".  In your particular example, I'd
>
>> BTW, if I ever write a new C-like language, ":=" will be the assignment
>> operator, "==" the comparison operator, and "=" totally invalid!  Although

If you are going to prevent assignment in a conditional, you are preventing
it from being an expression.  This stops things like "a=b=c=0;" from falling
out elegantly.  If you are deadset about making C have the cumbersome expressions
of pascal, you may as well drop the '++', '+=', '--', '-=' operators, and give
'and' a higher precidence than everything else (having decided && is too hard
to type properly).


--
Jeremy Fitzhardinge: jeremy at ultima.socs.uts.edu.au  | To make an omelette, you
No Comment.          jeremy at utscsd.csd.uts.edu.au   | gotta break eggs.
                                                    |                -J.Stalin



More information about the Comp.lang.c mailing list