将非`void`指针转换为`uintptr_t`,反之亦然 [英] Converting a non-`void` pointer to `uintptr_t` and vice-versa

查看:269
本文介绍了将非`void`指针转换为`uintptr_t`,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有两个相关的C标准规则:

There are two related C standard rules:

C99标准,6.3.2.3:

指向void的指针可以转换为任意指针 不完整或对象类型.指向任何不完整或对象类型的指针 可能会转换为指向void的指针并再次返回;结果应 比较等于原始指针.

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:

以下类型将无符号整数类型指定为 属性,可以将任何有效的指向void的指针转换为该类型, 然后转换回指向void的指针,结果将进行比较 等于原始指针: uintptr_t

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

这意味着符合以下代码:

It means, that the following code is compliant:

int *p = NULL;
void *q = (void*)p;
uintptr_t s = (uintptr_t)q;

但是它真的需要分两步进行吗?如果执行以下操作,编译器会执行隐式中间强制转换吗?

But does it really need the two-step cast? Will the compiler perform an implicit intermediate cast if doing something like:

int *p = NULL;
uintptr_t s = (uintptr_t)p;

(嗯,它可能适用于大多数编译器,但是我的问题是关于标准合规性的问题)

(Well, it probably will on most compilers, but my question is about standard compliance)

推荐答案

我不会冒险.该标准明确规定了允许和禁止的条件.

I wouldn't risk it. The standard makes it abundantly clear what is allowed and what is not allowed.

编写uintptr_t s = (uintptr_t)(void*)p;会向代码阅读器发出信号,表明您知道自己在做什么.

Writing uintptr_t s = (uintptr_t)(void*)p; signals to a reader of your code that you know what you're doing.

这篇关于将非`void`指针转换为`uintptr_t`,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆