?: grouping
Steve Summit
stevesu at azure.UUCP
Sun Jan 15 17:52:16 AEST 1984
I'm usually pretty bored with these nitty-gritty compiler
questions, because I don't want to think that hard, but now I'm
working on a compiler myself, and I came up with one.
How should ?: group? The C Reference Manual says it groups left
to right, just like all the binary operators. In the case of a
ternary operator it's not as obvious what "left to right" means,
but I would think that a?b:c?d:e should be evaluated as
(a?b:c)?d:e (do the leftmost one first). The first time I
implemented it, I ended up with something that would interpret it
as a?b:(c?d:e), for no other reason than because it was easier to
implement that way. Lo and behold, that's what the 4.1 compiler
does, too! As a quick example, the program
main()
{
printf("%d\n", 1?1:0?3:4);
}
prints 1. (1?1:0)?3:4 would be 3.
I'm not too worried about this, because the "compiler" I'm working
on is actually just a stripped-down version of cpp, and I'm
reasonably sure that nobody is ever going to use a ?: on an #if
line in this application. Still, it is a curious question.
Steve Summit
tektronix!tekmdp!stevesu
More information about the Comp.lang.c
mailing list