我可以将 unsigned long int 转换为 uintptr_t 吗?

问题描述 投票:0回答:1
uintptr_t uint_to_uintptr(unsigned int n) {
    return (uintptr_t)n;
}

uintptr_t ulint_to_uintptr(unsigned long int n) {
    return (uintptr_t)n;
}

uintptr_t ullint_to_uintptr(unsigned long long int n) {
    return (uintptr_t)n;
}

上面 3 种类型转换中哪一种不会导致信息(位)丢失?

c99标准说:

以下类型指定无符号整数类型,其属性是任何指向

void
的有效指针都可以转换为该类型,然后转换回指向
void
的指针,结果将与原始指针进行比较:

uintptr_t

但它没有指定这个

unsigned integer type
的大小是多少。

它是指最大宽度无符号整数类型(

UINTMAX_MAX
)的最大值还是简单的
unsigned int

c casting c99
1个回答
0
投票

您可以添加断言来检查您的代码是否不会在特定实现中调用 UB。

uintptr_t uint_to_uintptr(unsigned int n) {
    _Static_assert(sizeof(uintptr_t) >= sizeof(unsigned int), "uintptr_t is smaller than unsigned int");
    return (uintptr_t)n;
}

uintptr_t ulint_to_uintptr(unsigned long int n) {
    _Static_assert(sizeof(uintptr_t) >= sizeof(unsigned long int), "uintptr_t is smaller than unsigned long int");
    return (uintptr_t)n;
}

uintptr_t ullint_to_uintptr(unsigned long long int n) {
    _Static_assert(sizeof(uintptr_t) >= sizeof(unsigned long long int), "uintptr_t is smaller than unsigned long long int");
    return (uintptr_t)n;
}
© www.soinside.com 2019 - 2024. All rights reserved.