shashashamti2008
shashashamti2008

Reputation: 2327

Issue with C++ type casting

I am trying to typecast a float to unsigned char using the following C++ code:

#include <iostream>
int main()
{
        
    std::cout << int((unsigned char)((float)-10)) << "\n";
    std::cout << int((unsigned char)((float)300)) << "\n";
     
    return 0;
}

gcc 12.1 output:

0
255

which can be tried here. It nicely clamps the values to 0 and 255, and this is what I expect to get in any operating system. However, the problem occurs when I try the same code in Visual Studio 2022, which can be tried here.

Visual Studio output

246
44

It looks to me that 246 is actually 256-10 and the second output 44 is 300-256. May I know why Visual Studio is producing a different result?

How can I make this simple casting cross-platform?

Upvotes: 0

Views: 137

Answers (1)

n. m. could be an AI
n. m. could be an AI

Reputation: 119877

Floating-integral conversions [conv.fpint]

  1. A prvalue of a floating-point type can be converted to a prvalue of an integer type. The conversion truncates; that is, the fractional part is discarded. The behavior is undefined if the truncated value cannot be represented in the destination type.

Upvotes: 10

Related Questions