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

前端 未结 2 454
轻奢々
轻奢々 2020-12-17 14:44

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 i

相关标签:
2条回答
  • 2020-12-17 15:07

    Any quality general-purpose implementation will process conversions between uintptr_t and a non-void type as if they'd been converted through void*. The Standard treats behavior in this situation, and many others involving pointers, as a quality-of-implementation issue, and expects that people who are seeking to write quality implementations will be able to recognize situations where there's one obvious, sensible, and useful way for a program to behave without the Standard having to explicitly enumerate them all. They also recognize that it's possible to produce an implementation which is conforming but of such poor quality as to be useless.

    Although it would be possible to have an implementation where conversions between uintptr_t and any non-void pointer type behave in any arbitrary fashion of the implementer's choosing, anyone who produces an implementation where such conversions don't work in the typical fashion, and who fails to document a good reason for such difference, should be recognized as a vandal who is trying to undermine the language with their poor quality implementation. Programmers should feel no obligation to appease such behavior; unless or until it is seen for what is is, it will get worse and worse until the language becomes totally useless.

    0 讨论(0)
  • 2020-12-17 15:08

    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.

    0 讨论(0)
提交回复
热议问题