ternary operator

N

novickivan

Hello,

What does this print:

printf("%d\n", 3 ?: 4);

For me it seems to print the number 3. It seems the expression says
if the first expression is true than use the second expression as the
result. But if there is no second expression than use the first
expression.

I don't see this syntax (with the missing second expression)
referenced in the C language standard, so I was wondering if this is
official C language syntax?

Cheers,
Ivan Novick
 
K

Kenny McCormack

Hello,

What does this print:

printf("%d\n", 3 ?: 4);

CLC answer: A syntax error during compilation.

Real answer: It is a gcc extension.

--
No, I haven't, that's why I'm asking questions. If you won't help me,
why don't you just go find your lost manhood elsewhere.

CLC in a nutshell.
 
E

Eric Sosman

Hello,

What does this print:

printf("%d\n", 3 ?: 4);

For me it seems to print the number 3. It seems the expression says
if the first expression is true than use the second expression as the
result. But if there is no second expression than use the first
expression.

I don't see this syntax (with the missing second expression)
referenced in the C language standard, so I was wondering if this is
official C language syntax?

It is not. A conforming C implementation must issue a
diagnostic message.

You're probably using the popular gcc compiler, whose default
mode compiles a language that isn't exactly C, but "C with extras."
One of those extras is the construct you ask about: In gcc-dialect,
`x ?: y' is equivalent to `x ? x : y' (except that `x' is evaluated
only once).

To compile standard C with the gcc compiler, use a command-line
flag to specify the C version you intend: `-ansi' or `-std=c99',
usually. Consider using the `-pedantic' flag if your code is clean
enough to withstand it. I also recommend `-Wall -W'.
 
B

Ben Bacarisse

Eric Sosman said:
On 7/2/2010 10:47 AM, (e-mail address removed) wrote:
To compile standard C with the gcc compiler, use a command-line
flag to specify the C version you intend: `-ansi' or `-std=c99',
usually. Consider using the `-pedantic' flag if your code is clean
enough to withstand it.

gcc needs -pedantic to turn off its extensions (such as the one being
discussed). This may depend on the gcc version, but I think this is how
it has been for some time.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,085
Messages
2,570,597
Members
47,220
Latest member
AugustinaJ

Latest Threads

Top