• entries
    109
  • comments
    175
  • views
    116753

Playing with integers....

Sign in to follow this  
Emmanuel Deloget

247 views

I know I haven't updated my journal for a long time. I don't have much time by now, so I will only describe a small bug I just saw.

Consider this piece of code (32 bit integer is assumed):

void function()
{
try {
throw 0x80000000;
} catch (int a) {
std::cout << "catched a: " << std::hex << a << std::endl;
} catch (...) {
}

try {
throw 0x40000000;
} catch (int b) {
std::cout << "catched b: " << std::hex << b << std::endl;
} catch (...) {
}
}


What will be written on your console? Those who answered

catched a: 80000000
catched b: 40000000

Are WRONG.

Ah ah ah ah.
The correct answer is:


catched b: 40000000


Yes, the first one will not be catched. The reason lies in section 2.13.1.2 of the C++ ISO. The text reads:

Quote:

If it is octal or hexadecimal and has no suffix, it has the first of these type in which its value can be represented: int, unsigned int, long int, unsigned long int.


Here, the norm is not defined very well - obvioulsy it is possible to represent the 0x80000000 value by using an int. But some might choose to consider that -2147483648 is not a correct representation of 0x80000000, hence the promotion to unsigned int, which in turn makes our catch useless.

It was teh funnay to find, and teh funnay to fix.

Comming...


I'll have more time to spend during the next weeks, with some extra bonuses: updates of my ongoing "how to design this 2D graphic engine" series + the code which is related to this serie + some technical stuff I'm writing about image manipulation algorithm + a lot of other goodies.

Have a nice week-end!
Sign in to follow this  


1 Comment


Recommended Comments

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now