Overflow

  • Thread starter Gonçalo Rodrigues
  • Start date
G

Gonçalo Rodrigues

Hi all,

Suppose I have:

#include <climits>

const int val = INT_MAX;
val += 1;

Does the standard prescribe what happens with the above overflowing?
And if not, is there any *portable* way of discovering what happens?

Note: I've tested in my platform and the value val wrapps around.

TIA, with my best regards,
G. Rodrigues
 
T

Tim Love

Gonçalo Rodrigues said:
Suppose I have:
#include <climits>
const int val = INT_MAX;
val += 1;
Does the standard prescribe what happens with the above overflowing?
And if not, is there any *portable* way of discovering what happens?
Note: I've tested in my platform and the value val wrapps around.
Did you mean the const to be there? I get

Error 337: "foo.cc", line 5 # The left side of '+=' must be a modifiable lvalue.
val += 1;
^^^
 
S

Stefan Strasser

Gonçalo Rodrigues said:
Hi all,

Suppose I have:

#include <climits>

const int val = INT_MAX;
val += 1;

Does the standard prescribe what happens with the above overflowing?
And if not, is there any *portable* way of discovering what happens?

Note: I've tested in my platform and the value val wrapps around.


undefined behaviour
the standard even mentions systems which raise exceptions on
overflow(like x86 does on division by zero).
 
A

Alf P. Steinbach

* Gonçalo Rodrigues:
Suppose I have:

#include <climits>

const int val = INT_MAX;
val += 1;

Does the standard prescribe what happens with the above overflowing?

No.

It does however specify overflow behavior for unsigned integer types.

Where the value is reduced modulo 2^n, n the number of value representation
bits.

And if not, is there any *portable* way of discovering what happens?

Partially. std::numeric_limits<int>::is_modulo tells you whether the type
has wrapping behavior or not. However, if it doesn't (on nearly all modern
C++ implementation it will be wrapping, but _if_ it doesn't wrap) then that
still leaves the question of what happens on overflow, open.

Note: I've tested in my platform and the value val wrapps around.

Not very surprising; google for "two's complement".
 
G

Gonçalo Rodrigues

Did you mean the const to be there? I get

Error 337: "foo.cc", line 5 # The left side of '+=' must be a modifiable lvalue.
val += 1;
^^^

Of course not, bad cut and paste.

Regards,
G. Rodrigues
 

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

Similar Threads


Members online

Forum statistics

Threads
474,202
Messages
2,571,055
Members
47,658
Latest member
jaguar32

Latest Threads

Top