1

This code I was benchmarking and noticed it would not stop running when optimizations were turned on, im using Code Blocks with MinGW 4.7.0.

If I change the iterator to unsigned i; the loop will end with optimizations on. Otherwise I need to turn off optimizations to use the int i; declaration.

int main(void)
{
    int i;
    int a, b;
    a = 5; b = 24;
    for(i = 0; i < 2700000000; i++)
        asm_swap(&a, &b);
    return 0;
}

There is also a warning: this decimal constant is unsigned only in ISO C90 [enabled by default] apparently referring to the 2.7 billion constant. I do not think this would change anything as either int or unsigned can carry this value, which is part of why I am so confused here. I have no explanation.

What is the issue with having the int type and optimizations enabled?

4

2 回答 2

3

On your platform, int is 32 bits wide.

The largest signed 32-bit integer is 2,147,483,647. The largest unsigned 32-bit integer is 4,294,967,295.

Thus 2,700,000,000 would fit in an unsigned int, but would not fit in an int.

This means that when you use unsigned int, your program is well-defined. However, when you use int, the behaviour of your program is undefined.

于 2013-03-30T10:39:10.270 回答
1

If your platform is 32-bit your int will overflow and you will end up in undefined behavior land where anything might happen, including going on forever.

于 2013-03-30T10:40:40.317 回答