質問

My apologies if this question already exists, but I have not found it here on SO. That's why I ask it. Anyway...

Say you have following very simple method:

public int Square(int i)
{
    return i * i;
}

When I use the method like this:

int result = Square(Int32.MaxValue);
Console.WriteLine("Result: " + result);

This is the result:

Result: 1

Why does this compile and execute succesfully, and why is 1 returned?

役に立ちましたか?

解決 3

It compiles, but it runs to completion only in an unchecked context, which is the compiler default. Adding a checked block (or specifying the /checked compiler option) will give you an overflow exception at runtime.

If in an unchecked context, the result is 1 because the multiplication goes like this:

            0x ffff ffff
*           0x ffff ffff
= 0x ffff fffe 0000 0001

The high-order bits that overflow are discarded, leaving you with 0x 0000 0001.

他のヒント

This is because an int can not take a larger value than Int32.MaxValue. Int32.MaxValue * Int32.MaxValue is much lager than Int32.MaxValue, so the int variable will overflow.

You will notice a similar thing with int i = Int32.MaxValue + 1.

That's a simple overflow of integer value. By default overflow checking is disabled, but if you'll add checked block, then you'll see exception:

public int Square(int i)
{
    checked
    {
        return i * i;
    }
}

Why it's compiled? Because compiler can't check if overflow will occur. It can do that with compile-time constants:

int result = Int32.MaxValue * Int32.MaxValue;

But it can't invoke methods during compilation.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top