x +1 > x

S

Spiros Bousbouras

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 ?
 
T

Thomas Lumley

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




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
 
R

Richard Heathfield

Thomas Lumley said:

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.
 

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
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top