gpt4 book ai didi

C:乘以 uint16_t 时的未定义行为?

转载 作者:行者123 更新时间:2023-12-05 09:01:16 30 4
gpt4 key购买 nike

我已经意识到并读到将 uint16_t 与另一个 uint16_t 相乘会得到一个整数(它实际上似乎是一个带符号的整数?请参阅:)。鉴于此,我是否必须假设以下函数 f 会产生未定义的行为,因为会有符号整数溢出?

会发生溢出,因为 x=45000x*x 导致“几乎” INT32_MAX,如果它会溢出再次乘以 x

(顺便说一句:在我的平台上 intint32_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);
}

会发生溢出,因为 x=45000x*x 导致“几乎” INT32_MAX,如果它会溢出再次乘以 x

这是正确的,还是我做了一些错误的假设?

最佳答案

do I have to assume that the following function f produces undefined behavior, because there'll be a signed integer overflow?

是的,在 32 位 int/unsigned 实现上。 16 位 int/unsigned 上没有符号整数溢出。

The overflow would occur, because x*x for x=45000 results in "almost" INT32_MAX and it will then overflow if it is multiplied again by x.

是的,int 溢出是未定义的行为 (UB)。

为避免 int 溢出 UB,请使用 unsigned 数学并让编译器生成高效代码。适用于 int/unsigned 作为 16、32、... 位宽。

// return x * x * x;
return 1u * x * x * x; // Coerce into using unsigned math

关于C:乘以 uint16_t 时的未定义行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73600275/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com