Is incrementing a null pointer well-defined?

后端 未结 9 452
情话喂你
情话喂你 2020-12-03 04:17

There are lots of examples of undefined/unspecified behavior when doing pointer arithmetics - pointers have to point inside the same array (or one past the end), or inside t

9条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-03 05:00

    As said by Columbo it is UB. And from a language lawyer point of view this is the definitive answer.

    However all C++ compiler implementations I know will give same result :

    int *p = 0;
    intptr_t ip = (intptr_t) p + 1;
    
    cout << ip - sizeof(int) << endl;
    

    gives 0, meaning that p has value 4 on a 32 bit implementation and 8 on a 64 bits one

    Said differently :

    int *p = 0;
    intptr_t ip = (intptr_t) p; // well defined behaviour
    ip += sizeof(int); // integer addition : well defined behaviour 
    int *p2 = (int *) ip;      // formally UB
    p++;               // formally UB
    assert ( p2 == p) ;  // works on all major implementation
    

提交回复
热议问题