Re: How to cast int to short



Jon Skeet [C# MVP] wrote:
Derrick Coetzee [MSFT] <dcoetzee@xxxxxxxxxxxxxxxxxxxx> wrote:
myFun ((short)i);

Note that, by default, C# checks for integer overflow when
performing a cast in this obvious way. [...]

No, by default C# *doesn't* check for overflow, except for
compile-time constant expressions.

Sorry, my mistake - I'm used to this option being on. I do personally
recommend that the /checked option (Build->Advanced->Check for arithmetic
overflow/underflow) is always used, as this can help to find bugs and
prevent potential security issues, as well as provide conceptual safety
guarantees (and I think it should be on by default). If profiling reveals
that they're slowing down a bottleneck, or if you want the C behaviour of
arithmetic mod 2^word size, you can always wrap the relevant code in
unchecked { }. Thanks for the correction, Jon.
--
Derrick Coetzee, MCAD, MSFT (Speech Server)
This posting is provided "AS IS" with no warranties, and confers no
rights.


.



Relevant Pages

  • Re: Why would you not use "checked"?
    ... > There are some algorithms that actually use the overflow (rely on it to ... Jon Skeet - ... If replying to the group, please do not mail me too ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Factorial
    ... You could cast a Variant variable as a Decimal type ... Variant and CDec a number into it to make it the ... they will produce an overflow error. ... if a Variant variable is assigned a value that was cast ...
    (microsoft.public.vb.general.discussion)
  • Re: Cannot compile with _FILE_OFFSET_BITS = 64
    ... No automatic conversion to 64 bit type is done by compiler. ... the second one might overflow, ... to use a cast to off_t rather than the "LL" suffix. ... Or you could apply the cast to all four constants, ...
    (comp.lang.c)
  • Re: integer overflow
    ... "Ashutosh Iddya" wrote in message ... > I am performing an integer count of a particular operation in my program. ... > After a sufficiently large value an overflow occurs. ... Any help in this regard would be greatly appreciated. ...
    (comp.lang.c)
  • Re: cast unsigned long to long
    ... > The cast is unnecessary; ... An example of undefined behavior is the behavior on integer overflow. ...
    (comp.lang.c)