if vs ?: - (nf)

emjej at uokvax.UUCP emjej at uokvax.UUCP
Thu Feb 23 14:09:48 AEST 1984


#R:iuvax:9500002:uokvax:3000019:000:1536
uokvax!emjej    Feb 17 11:35:00 1984

/***** uokvax:net.lang.c / iuvax!apratt / 12:44 am  Feb 15, 1984 */
.... With that in mind, can anybody tell me the likely difference between
	if ( i )
		j++;
	else
		k++;

and
	i ? j++ : k++ ;

...?  Surely there will be differences in the compiled code.. Can somebody
tell me what they are likely to be?
/* ---------- */

I can only tell you what the difference would be in my code generator.
The latter code (?:) would generate worse code in this context, since
it looks locally like someone is going to use the results of the conditional
expression. The if/else would look like

	cmp	0,<i>
	jeq	Ln
	inc	1,<j>
	jbr	L(n+1)
Ln:	inc	1,<k>
L(n+1):	...

while the ?: would look like

	cmp	0,<i>
	jeq	Ln
	mov	<j>,t0		a temporary register
	inc	1,<j>
	jbr	L(n+1)
Ln:	mov	<k>,t0
	inc	1,<k>
L(n+1):	...

(The comparison might not be there if we knew that we'd just evaluated i
so as to set flags.) All it means is that I'm not bright enough to notice
that you're not using the old values of j and k for the conditional
expression, and that I'm generating code for a machine whose addressing
modes don't have side-effects. (It was fun to implement post-increment
and decrement so as to avoid unnecessary copies, by the way--you just
remember how much to tweak things just before discarding them. Watch
out for base registers used to access things that you want to compare,
because deferring increments on them may wipe out the condition code!
In that case, just bias the offset by the increment amount and do it
right away.)

						James Jones



More information about the Comp.lang.c mailing list