[comp.lang.c] Ternary Operator:

tanner@cdis-1.compu.com (Dr. T. Andrews) (06/02/90)

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);
-- 
uflorida!ki4pv!cdis-1!tanner {uunet dsinc}!cdin-1!cdis-1!tanner

diamond@tkou02.enet.dec.com (diamond@tkovoa) (06/04/90)

In article <000019B@cdis-1.compu.com> tanner@cdis-1.compu.com writes:

>	char		nonconst_str[10];
>	const char	const_str[10] = "123456789";
>	blunge = printf("%s\n", cond ? const_str : nonconst_str);

It is legal.  The expression (cond ? const_str : nonconst_str) has
type (const char *).

-- 
Norman Diamond, Nihon DEC     diamond@tkou02.enet.dec.com
Proposed group comp.networks.load-reduction:  send your "yes" vote to /dev/null.

steve@taumet.COM (Stephen Clamage) (06/04/90)

In article <000019B@cdis-1.compu.com> tanner@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@taumet.com