Unchecking Overflows

I recently ran into a new (for me) compiler error from the following line of code:

UInt16 section_length = (UInt16)(SizeOfSection - 3);

where SizeOfSection is a UInt32.  The error messages were as follows:

1. The operation overflows at compile time in checked mode
2. Constant value '4294967293' cannot be converted to a 'ushort' (use 'unchecked' syntax to override)

Strangely, even though these were marked as compilation errors, the code compiled and ran correctly.

Anyway, the fix was (as suggested) to use the unchecked syntax:

UInt16 section_length = unchecked((UInt16)(SizeOfSection - 3));

The bizarre thing about this, though, is that other code that casts UInt32 to UInt16 didn’t produce this error, so I would be interested to know what triggered it in this case…

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s