Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C Programming > x +1 > x

Reply
Thread Tools

x +1 > x

 
 
Spiros Bousbouras
Guest
Posts: n/a
 
      09-15-2007
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 ?

 
Reply With Quote
 
 
 
 
Thomas Lumley
Guest
Posts: n/a
 
      09-15-2007
On Sep 15, 6:41 am, Spiros Bousbouras <spi...@gmail.com> 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

 
Reply With Quote
 
 
 
 
Richard Heathfield
Guest
Posts: n/a
 
      09-15-2007
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
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off




Advertisments