Ternary Operator: (cond ? const_str : nonconst_str) legal?

Stephen Clamage steve at taumet.COM
Tue Jun 5 01:54:46 AEST 1990


In article <000019B at cdis-1.compu.com> tanner at cdis-1.compu.com writes:
>Given:
>	char		nonconst_str[10];
>	const char	const_str[10] = "123456789";
>	int		cond, blunge;
>Is the following legal?
>	blunge = printf("%s\n", cond ? const_str : nonconst_str);

Yes, if you also #include <stdio.h>.  The type of const_str in this context
is "pointer to const char", and the type of nonconst_str is "pointer to
char".  The ANSI standard allows both sides of the ":" to point to qualified
or unqualified versions of compatible types; the result is the union of
the qualifications.  In this case, it is "pointer to const char".  This
is exactly the type of the first parameter to printf.

If you have a non-ANSI compiler, it probably will allow this, but there is
no telling.  That's what's so nice about a standard.
-- 

Steve Clamage, TauMetric Corp, steve at taumet.com



More information about the Comp.lang.c mailing list