Is pointer tagging in C undefined according to the standard?

后端 未结 2 1040
逝去的感伤
逝去的感伤 2020-12-15 09:34

Some dynamically-typed languages use pointer tagging as a quick way to identify or narrow down the runtime type of the value being represented. A classic way to do this is t

2条回答
  •  死守一世寂寞
    2020-12-15 10:08

    You're right about the relevant parts of the standard. For reference:

    An integer may be converted to any pointer type. Except as previously specified, the result is implementation-defined, might not be correctly aligned, might not point to an entity of the referenced type, and might be a trap representation.

    Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type.

    Since the conversions are implementation defined (except when the integer type is too small, in which case it's undefined), there's nothing the standard is going to tell you about this behaviour. If your implementation makes the guarantees you want, you're set. Otherwise, too bad.

    I guess the answer to your explicit question:

    Is it possible to guarantee this according to the letter of the standard?

    Is "yes", since the standard punts on this behaviour and says the implementation has to define it. Arguably, "no" is just as good an answer for the same reason.

提交回复
热议问题