x +1 > x

Discussion in 'C Programming' started by Spiros Bousbouras, Sep 15, 2007.

  1. In the thread "Eventual undefined behaviour" Harald van Dijk
    said:

    > The standard allows


    > int f(int x) {
    > return x + 1 > x;
    > }
    >
    > to be optimised to
    >
    > int f(int x) {
    > return 1;
    > }


    How does this follow from the standard ? And what would
    happen if x was unsigned int ?
     
    Spiros Bousbouras, Sep 15, 2007
    #1
    1. Advertising

  2. On Sep 15, 6:41 am, Spiros Bousbouras <> wrote:
    > In the thread "Eventual undefined behaviour" Harald van Dijk
    > said:
    >
    > > The standard allows
    > > int f(int x) {
    > > return x + 1 > x;
    > > }

    >
    > > to be optimised to

    >
    > > int f(int x) {
    > > return 1;
    > > }

    >
    > How does this follow from the standard ? And what would
    > happen if x was unsigned int ?



    If 'x' is not INT_MAX then f() must return 1, and if 'x is INT_MAX the
    behaviour is undefined and so f() is permitted to return 1. Then by
    the 'as if' rule, the function can compute the return value of 1 in
    any way.

    With unsigned int the optimization would not be permitted, since the
    behaviour on overflow is defined and implies a return value of 0.


    -thomas
     
    Thomas Lumley, Sep 15, 2007
    #2
    1. Advertising

  3. Thomas Lumley said:

    <snip>

    > With unsigned int the optimization would not be permitted, since the
    > behaviour on overflow is defined and implies a return value of 0.


    Not quite a correct explanation. The C Standard does not define the
    behaviour of unsigned ints on overflow. Rather, it specifies unsigned
    integer arithmetic in such a way that overflow is impossible.

    Your description of the outcome, however, is correct.

    --
    Richard Heathfield <http://www.cpax.org.uk>
    Email: -www. +rjh@
    Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
    "Usenet is a strange place" - dmr 29 July 1999
     
    Richard Heathfield, Sep 15, 2007
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.

Share This Page