Correct parsing of ternary operator.
Walter Murray
walter at hpclwjm.HP.COM
Fri Jan 5 10:35:03 AEST 1990
Mike Lijewski writes:
> Consider the following code:
> main()
> {
> int a = 0, b = 1, c = 2;
> c ? c = a : c = b;
> exit(0);
> }
> According to the precedence rules of C, the conditional expression
> should be evaluated as:
> (c ? c = a : c) = b;
> which should produce and error. Well, it happens that I have a
> compiler which accepts this and produces results which suggest
> to me that it is evaluating this expression as:
> c ? c = a :(c = b);
> The vendor seems unwilling to accept this as a bug.
If your vendor claims conformance to the forthcoming ANSI standard,
the answer is easy: the program is illegal. An ANSI-conforming
compiler will produce a diagnostic. If it chooses to make the
diagnostic a warning, it is free to proceed and generate whatever
code it pleases. The only requirement is that a diagnostic be
produced.
If ANSI conformance is not claimed, the answer is a little harder.
Does the vendor provide a programmer's reference manual that describes
what the behavior should be?
> Am I just being pedantic, or is this a serious bug?
You gave the compiler an expression that you admit is illegal.
The compiler interpreted the expression in a way that would make
sense to a lot of programmers. I wouldn't call that a serious
bug. Some people would call it a feature.
It all boils down to a question of whether the expression is
bad enough to evoke a diagnostic from the compiler, and that's
a matter of opinion. (ANSI says Yes.) Does your compiler have
an option to make it more verbose about questionable constructs?
Try lint; it will probably catch the error.
> I haven't been able to come up with an example of correct usage
> of the ternary operator, which produces incorrect code.
Keep trying.
> If anyone knows of some code which might clearly prove that
> this is a bug, I would sure appreciate receiving it.
For what it's worth, Harbison & Steele (C: A Reference Manual)
clearly state that the expression is illegal (2nd ed., p. 182).
Walter Murray
----------
More information about the Comp.lang.c
mailing list