Kev*_*ier 2 c undefined-behavior signed-overflow
我已经意识到并读到将 auint16_t与另一个uint16_t相乘会得到一个整数(它实际上似乎是一个有符号整数?请参阅:)。鉴于此,我是否必须假设以下函数f会产生未定义的行为,因为会出现有符号整数溢出?
会发生溢出,因为x*x对于x=45000“几乎”的结果INT32_MAX,如果再次乘以 就会溢出x。
(顺便说一句:在我的平台上int是一个int32_t)
#include <stdio.h>
#include <stdint.h>
uint16_t f(uint16_t x) {
printf("%zu\n", sizeof(x)); // <-- 2
printf("%zu\n", sizeof(x * x)); // <-- 4
return x * x * x;
}
int main()
{
uint16_t x = 45000;
uint16_t y = f(x);
}
Run Code Online (Sandbox Code Playgroud)
会发生溢出,因为x*x对于x=45000“几乎”的结果INT32_MAX,如果再次乘以 就会溢出x。
这是正确的,还是我做出了一些错误的假设?
do I have to assume that the following function f produces undefined behavior, because there'll be a signed integer overflow?
Yes, on 32-bit int/unsigned implementations. No signed integer overflow on 16-bit int/unsigned ones.
The overflow would occur, because x*x for x=45000 results in "almost"
INT32_MAXand it will then overflow if it is multiplied again by x.
Yes and int overflow is undefined behavior (UB).
To avoid int overflow UB, use unsigned math and let the compiler emit efficient code. Works well for int/unsigned as 16, 32, ... bit widths.
// return x * x * x;
return 1u * x * x * x; // Coerce into using unsigned math
Run Code Online (Sandbox Code Playgroud)