-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Pádraig Brady wrote:
> I was wondering under what circumstances
> (compilers/CPUs) that the following program
> generates an integer overflow exception.
> I think none, but I'm reviewing code
> that assumes otherwise.
> I understand MIPS generates an exception
> for signed arithmetic only.
>> #include <stdio.h>
> int main(void)
> {
> unsigned int i;
> for(;;i++;) {
> if (i==0) {
> printf("wrap\n");
> fflush(stdout);
> }
> }
> }
IMHO that could doesn't work anyway. It is not mandatory for a
compiler to initialize any variables, as such the above code will be
random. Though it does accomplish your mission.
The only way to avoid this is to always test after or before an
increase if your value still fits inside the maximums. That works on
all platforms and on all cases. Easiest way is:
unsigned int prev_i = i;
i++;
if (i < prev_i) printf("wrapped!");
I actually am pretty sure a lot of software does not account for this.
Lots of people (me included :) simply use uint64_t ;)
They can wrap, but it should not quickly happen.
If you really want to avoid that you can always use a long double or
something which will nicely scale away the larger it gets.
All depends for what application you need this.
Greets,
Jeroen
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.7 (MingW32)
Comment: Jeroen Massar / http://unfix.org/~jeroen/
iHUEARECADUFAkZlpBIuFIAAAAAAFQAQcGthLWFkZHJlc3NAZ251cGcub3JnamVy
b2VuQHVuZml4Lm9yZwAKCRApqihSMz58I1udAJ0Q0cYifOCrqDn111EGjYv8xce1
vwCgrKof81OJ3AJBoYiIigZjWws6s8Y=
=Qr11
-----END PGP SIGNATURE-----
Maintained by the ILUG website team. The aim of Linux.ie is to
support and help commercial and private users of Linux in Ireland. You can
display ILUG news in your own webpages, read backend
information to find out how. Networking services kindly provided by HEAnet, server kindly donated by
Dell. Linux is a trademark of Linus Torvalds,
used with permission. No penguins were harmed in the production or maintenance
of this highly praised website. Looking for the
Indian Linux Users' Group? Try here. If you've read all this and aren't a lawyer: you should be!