Connecting Tech Pros Worldwide Forums | Help | Site Map

Is this Ok? (?:)

Jerald Fijerald
Guest
 
Posts: n/a
#1: Nov 14 '05
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 [i] > 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.
Joona I Palaste
Guest
 
Posts: n/a
#2: Nov 14 '05

re: Is this Ok? (?:)


Jerald Fijerald <jfj@freemail.gr> scribbled the following:[color=blue]
> Hi all.[/color]
[color=blue]
> I was wondering if this expression is ok and has not any undefined
> behaviors (bad style is not an issue):[/color]
[color=blue]
> int x;
> x = a [i] > 0 ? a [i++] : 1000;[/color]
[color=blue]
> I believe it is ok because in the case[/color]
[color=blue]
> x ? i++ : 0;[/color]
[color=blue]
> 'i' is not incremented if x==0.
> So it is ok, yes?[/color]

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

--
/-- Joona Palaste (palaste@cc.helsinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"No, Maggie, not Aztec, Olmec! Ol-mec!"
- Lisa Simpson
Dan Pop
Guest
 
Posts: n/a
#3: Nov 14 '05

re: Is this Ok? (?:)


In <c6angc$cg3$1@oravannahka.helsinki.fi> Joona I Palaste <palaste@cc.helsinki.fi> writes:
[color=blue]
>Jerald Fijerald <jfj@freemail.gr> scribbled the following:[color=green]
>> Hi all.[/color]
>[color=green]
>> I was wondering if this expression is ok and has not any undefined
>> behaviors (bad style is not an issue):[/color]
>[color=green]
>> int x;
>> x = a [i] > 0 ? a [i++] : 1000;[/color]
>[color=green]
>> I believe it is ok because in the case[/color]
>[color=green]
>> x ? i++ : 0;[/color]
>[color=green]
>> 'i' is not incremented if x==0.
>> So it is ok, yes?[/color]
>
>This is completely OK, safe, kosher and hunky-dory. The ?: operator
>constitutes a sequence point, so a[i]>0 is guaranteed to have fully
>evaluated before either a[i++] or 1000 can begin evaluating.[/color]

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[i] > 0) x = a[i++];
else x = 1000;

in the abstract C machine.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Dan.Pop@ifh.de
Closed Thread


Similar C / C++ bytes