将非“void”指针转换为“uintptr_t”,反之亦然
Converting a non-`void` pointer to `uintptr_t` and vice-versa
有两个相关的C标准规则:
C99 标准,6.3.2.3
:
A pointer to void may be converted to or from a pointer to any
incomplete or object type. A pointer to any incomplete or object type
may be converted to a pointer to void and back again; the result shall
compare equal to the original pointer.
和7.20.1.4
:
The following type designates an unsigned integer type with the
property that any valid pointer to void can be converted to this type,
then converted back to pointer to void, and the result will compare
equal to the original pointer:
uintptr_t
这意味着,以下代码是兼容的:
int *p = NULL;
void *q = (void*)p;
uintptr_t s = (uintptr_t)q;
但真的需要两步施法吗?如果执行以下操作,编译器是否会执行隐式中间转换:
int *p = NULL;
uintptr_t s = (uintptr_t)p;
(好吧,它可能适用于大多数编译器,但我的问题是关于标准合规性)
我不会冒险。该标准非常清楚什么是允许的,什么是不允许的。
向代码的 reader 写入 uintptr_t s = (uintptr_t)(void*)p;
信号表明您知道自己在做什么。
任何高质量的通用实现都会处理 uintptr_t
和非 void 类型之间的转换,就好像它们是通过 void*
转换的一样。
该标准将这种情况下的行为以及许多其他涉及指针的行为视为实现质量问题,并期望寻求编写高质量实现的人能够识别存在一种明显、明智且有用的方法的情况一个程序在没有标准必须显式枚举它们的情况下运行。他们还认识到有可能产生一个符合要求但质量很差以至于无用的实现。
虽然可以实现 uintptr_t
和任何非 void 指针类型之间的转换以实现者选择的任意方式运行,但任何产生此类转换的实现的人都不会以典型的方式工作,并且未能记录这种差异的充分理由的人,应该被认为是破坏者,他们试图通过低质量的实现来破坏语言。程序员不应该觉得有义务安抚这种行为;除非或直到看到它的本来面目,否则它会变得越来越糟,直到语言变得完全无用。
有两个相关的C标准规则:
C99 标准,6.3.2.3
:
A pointer to void may be converted to or from a pointer to any incomplete or object type. A pointer to any incomplete or object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.
和7.20.1.4
:
The following type designates an unsigned integer type with the property that any valid pointer to void can be converted to this type, then converted back to pointer to void, and the result will compare equal to the original pointer:
uintptr_t
这意味着,以下代码是兼容的:
int *p = NULL;
void *q = (void*)p;
uintptr_t s = (uintptr_t)q;
但真的需要两步施法吗?如果执行以下操作,编译器是否会执行隐式中间转换:
int *p = NULL;
uintptr_t s = (uintptr_t)p;
(好吧,它可能适用于大多数编译器,但我的问题是关于标准合规性)
我不会冒险。该标准非常清楚什么是允许的,什么是不允许的。
向代码的 reader 写入 uintptr_t s = (uintptr_t)(void*)p;
信号表明您知道自己在做什么。
任何高质量的通用实现都会处理 uintptr_t
和非 void 类型之间的转换,就好像它们是通过 void*
转换的一样。
该标准将这种情况下的行为以及许多其他涉及指针的行为视为实现质量问题,并期望寻求编写高质量实现的人能够识别存在一种明显、明智且有用的方法的情况一个程序在没有标准必须显式枚举它们的情况下运行。他们还认识到有可能产生一个符合要求但质量很差以至于无用的实现。
虽然可以实现 uintptr_t
和任何非 void 指针类型之间的转换以实现者选择的任意方式运行,但任何产生此类转换的实现的人都不会以典型的方式工作,并且未能记录这种差异的充分理由的人,应该被认为是破坏者,他们试图通过低质量的实现来破坏语言。程序员不应该觉得有义务安抚这种行为;除非或直到看到它的本来面目,否则它会变得越来越糟,直到语言变得完全无用。