less than comparison for void pointers

后端 未结 3 2034
梦谈多话
梦谈多话 2020-12-19 17:51

I want to compare two void pointers like this:

void foo(void* p1, void* p2) {

  if (p1 < p2) {
    void *tmp = p1;
    p1 = p2;
    p2 = tmp;
  }

  // d         


        
3条回答
  •  我在风中等你
    2020-12-19 17:58

    Following on from @BoBTFish... for Relational Operators (6.5.8 of C11) things are limited further:

    Constraints 2

    One of the following shall hold:

    — both operands have real type;

    or — both operands are pointers to qualified or unqualified versions of compatible object types.

    Which one reads as excluding void* (void is not a type, so void* is not a pointer to a type)... so your compiler may well whine at you if you try to < etc two void* pointers or one "real" pointer and a void*. Casting to (char*) will usually get the job done ! But like any cast, nobody is going to be very sympathetic if it crashes and burns :-)

    BTW, the standard is not an easy read, but at $60 it's a useful addition to one's library http://webstore.ansi.org/RecordDetail.aspx?sku=INCITS%2FISO%2FIEC+9899-2012

提交回复
热议问题