Is this Ok? (?:)

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Jerald Fijerald

    #1

    Is this Ok? (?:)

    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

    #2
    Re: Is this Ok? (?:)

    Jerald Fijerald <jfj@freemail.g r> 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.hel sinki.fi) ------------- Finland --------\
    \-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
    "No, Maggie, not Aztec, Olmec! Ol-mec!"
    - Lisa Simpson

    Comment

    • Dan Pop

      #3
      Re: Is this Ok? (?:)

      In <c6angc$cg3$1@o ravannahka.hels inki.fi> Joona I Palaste <palaste@cc.hel sinki.fi> writes:
      [color=blue]
      >Jerald Fijerald <jfj@freemail.g r> 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

      Comment

      Working...