Reputation: 55
Sample code is like this.
{
uint32_t x;
double y;
y = -1; // any negative number;
x = (uint32_t)(y);
print_log("%u", x);// here, x will be outputed, and it's 0;
}
Why will x be 0?
I run the same code in linux-gcc, the result is different.
Upvotes: 0
Views: 400
Reputation: 263357
The double
value -1.0
is outside the range of uint32_t
.
Converting a signed or unsigned integer value to an unsigned integer type has well-defined behavior. The result is wrapped to the range of the target type (reduced modulo MAX+1, where MAX is the maximum value of the target type).
Converting an out-of-range floating-point value to an integer type has undefined behavior. It's not surprising that the result varies from one system to another. In principle, it could even crash your program.
Once you decide what result you want given an input of -1.0
, you can figure out how to generate that result without undefined behavior.
Upvotes: 1