Can two different objects with automatic storage duration compare equal under address comparison?

前端 未结 1 1005
伪装坚强ぢ
伪装坚强ぢ 2021-01-12 02:50

In particular, is it allowed for the addresses of two automatic variables in different functions to compare equal as follows:

sink.c



        
相关标签:
1条回答
  • 2021-01-12 03:54

    The C11 standard part 6.5.9/6 says:

    Two pointers compare equal if and only if both are null pointers, both are pointers to the same object (including a pointer to an object and a subobject at its beginning) or function, both are pointers to one past the last element of the same array object, or one is a pointer to one past the end of one array object and the other is a pointer to the start of a different array object that happens to immediately follow the first array object in the address space.

    In this code none of the listed conditions hold; &f1 and &f2 are pointers to different objects, and one is not a subobject of the other.

    So the pointers must not compare equal. The compiler reporting equal is non-conforming.


    Note: If anyone has doubts about the legality of Foo f1 = make(&f1);, see this question. It is fine and the automatic object's lifetime begins at the preceding {.

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