整数和指针有什么区别?
来源标题:What's the difference between an integer and a pointer?
这是一条技术问答类内容,讨论整数与指针在编程中的区别。
以下正文同步自 Hacker News 最新,版权归原站所有,已转换为易读排版。
The Standard does not require that implementations define intptr_t nor uintptr_t. It also does not require that implementations define integer-to-pointer conversions in any meaningful fashion unless they define those types. Conforming implementations are certainly allowed to document some integer-to-pointer conversions as yielding trap representations, and nothing would prohibit an implementation that doesn’t define intptr_t nor uintptr_t from documenting them all as doing so, nor from saying that no pointers that aren’t trap representations can be represented with any integer type. On such an implementation, the issues you mention simply would not exist.
Consequently, since it would be rare for programs to convert pointers to integer type except when they needed to do “weird” things with them, I would think the simplest approach would be to specify that a conforming implementation may define types intptr_t and uintptr_t only if it treats the result of integer-to-pointer conversions as pointers of “officially unknowable” provenance at the time of derivation, and allows them to be used to access the storage associated with any object until the next time that either:
-
The storage is accessed in conflicting fashion via pointer not derived from that cast integer.
-
Some other pointer is derived, not from that cast integer, which will be used to either access the storage in conflicting fashion or derive another pointer that will be used to do so, etc.
-
Execution reaches enters a function or reaches the start of a loop iteration where one of the above occurs.
Implementations which would be incapable of supporting such semantics for a uintptr_t and intptr_t types would be free to either refrain from defining the types. If there is significant need for such types in code that doesn’t need any of the semantics, implementations that can’t support the semantics could define the types if user code defines a macro “__STDC_WAIVE_UINTPTR_GUARANTEES” before including a header that would define them.
正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。