What is the C++ equivalent of the C# checked

2020-07-22 09:24发布

问题:

I'm looking to avoid an overflow in managed C++ (CLI). In C# there is an unchecked keyword, and in C++ overflows do not end up in exceptions.

For reference, unchecked is documented here. Basically if you do:

unchecked
{
      int1 = 2147483647 + 10; //this overflows in CLI but is ok in C# and C++
}

In C# it will not overflow but convert to int by taking the least significant bits. This is appropriate when you compute hash codes for example.

Note: I realize there is no equivalent C++ keyword, but some bit shifting should do the trick;

回答1:

You can just use #pragma unmanaged around a method to get the normal unchecked behavior in native C++.



回答2:

Use an unsigned data type for bit operations and checksumming. Wrap-around behavior of unsigned behavior is well-defined in C++.