Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++, what happens when I use static_cast<char> on an integer value outside -128,127 range?

Tags:

c++

linux

g++

In a code compiled on i386 Linux using g++, I have used static_cast<char>() cast on a value that might exceed the valid range of -128,127 for a char. There were no errors or exceptions and so I used the code in production.

The problem is now I don't know how this code might behave when a value outside this range is thrown at it. There is no problem if data is modified or truncated, I only need to know how this modification behaves on this particular platform.

Also what would happen if C-style cast ((char)value) had been used? would it behave differently?

like image 972
zaadeh Avatar asked Mar 19 '23 05:03

zaadeh


1 Answers

In your case this would be an explicit type conversion. Or to be more precise an integral conversions.
The standard says about this(4.7):

If the destination type is signed, the value is unchanged if it can be represented in the destination type (and bit-field width); otherwise, the value is implementation-defined.

So your problem is implementation-defined. On the other hand I have not yet seen a compiler that does not just truncate the larger value to the smaller one. And I have never seen any compiler that uses the rule mentioned above. So it should be fairly safe to just cast your integer/short to the char.

I don't know the rules for an C cast by heart and I really try to avoid them because it is not easy to say which rule will kick in.

like image 98
mkaes Avatar answered Mar 26 '23 02:03

mkaes