UInt64 and "The operation overflows at compile time in checked mode" - CS0220
Asked Answered
G

3

16

This feels like a stupid question, but I can't seem to see the answer. I have an UInt64, which is supposed to have a max value of

UInt64.MaxValue 18446744073709551615

However, when I try to assign a modest-sized number, I get this overflow error of "The operation overflows at compile time in checked mode". If I wrap it in an "unchecked" block then it compiles, and runs as if this variable is zero:

UInt64 value1 = 1073741824 * 8; // Compile error CS0220
UInt64 value2 = 8589934592;     // Actual value - no error

Why is this happenning?

Genetic answered 15/4, 2012 at 23:52 Comment(1)
Ahh yes - that would absolutely explain it! Thanks guys!Genetic
P
33

Because:

UInt64 value1 = 1073741824 * 8;

Is doing the arithmetic as a signed 32-bit integer, then converting it to an ulong. Try:

UInt64 value1 = 1073741824UL * 8;

The UL means that the literal is of an unsigned long. See section 2.4.4 of the C# Specification for more on literal suffixes:

If the literal is suffixed by UL, Ul, uL, ul, LU, Lu, lU, or lu, it is of type ulong

Primal answered 15/4, 2012 at 23:54 Comment(0)
L
4

1073741824 is an int, not a UInt64.
Therefore, your multiplication overflows the limit of a 32-bit signed integer.

Add the ul (unsigned long) suffix to either operand.

Liaoyang answered 15/4, 2012 at 23:54 Comment(0)
M
1

You've got an error because you operate with int instead of long 1073741824 is still int (max for int is 2147483647).
So in first case you get overflow of int type.
Change first expression with:

UInt64 value1 = 1073741824L * 8;

and problem will disappear.

Minute answered 15/4, 2012 at 23:59 Comment(1)
didn't notice you operate with unsigned value. For unsigned long you should use 1073741824UL instead of 1073741824L.Minute

© 2022 - 2024 — McMap. All rights reserved.