Is this Ok? (?:)

J

Jerald Fijerald

Hi all.

I was wondering if this expression is ok and has not any undefined
behaviors (bad style is not an issue):

int x;
x = a > 0 ? a [i++] : 1000;

I believe it is ok because in the case

x ? i++ : 0;

'i' is not incremented if x==0.
So it is ok, yes?

Thanks,

Gerald.
 
J

Joona I Palaste

Jerald Fijerald said:
I was wondering if this expression is ok and has not any undefined
behaviors (bad style is not an issue):
int x;
x = a > 0 ? a [i++] : 1000;

I believe it is ok because in the case
x ? i++ : 0;
'i' is not incremented if x==0.
So it is ok, yes?

This is completely OK, safe, kosher and hunky-dory. The ?: operator
constitutes a sequence point, so a>0 is guaranteed to have fully
evaluated before either a[i++] or 1000 can begin evaluating.
 
D

Dan Pop

In said:
Jerald Fijerald said:
I was wondering if this expression is ok and has not any undefined
behaviors (bad style is not an issue):
int x;
x = a > 0 ? a [i++] : 1000;

I believe it is ok because in the case
x ? i++ : 0;
'i' is not incremented if x==0.
So it is ok, yes?

This is completely OK, safe, kosher and hunky-dory. The ?: operator
constitutes a sequence point, so a>0 is guaranteed to have fully
evaluated before either a[i++] or 1000 can begin evaluating.


More precisely, there is a sequence point after the evaluation of the
condition of the ?: operator, so this statement is the equivalent of

if (a > 0) x = a[i++];
else x = 1000;

in the abstract C machine.

Dan
 

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

No members online now.

Forum statistics

Threads
474,141
Messages
2,570,817
Members
47,367
Latest member
mahdiharooniir

Latest Threads

Top