Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
709 views
in Technique[技术] by (71.8m points)

c - Converting a non-`void` pointer to `uintptr_t` and vice-versa

There are two related C standard rules:

C99 standard, 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.

And 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

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...