Does applying post-decrement on a pointer already addressing the base of an array invoke undefined behavior?

后端 未结 1 857
走了就别回头了
走了就别回头了 2020-12-11 04:55

After hunting for a related or duplicate question concerning the following to no avail (I can only do marginal justice to describe the sheer number of pointer-arithmetic and

相关标签:
1条回答
  • 2020-12-11 05:34

    I am pretty certain that the result of the post-decrement in this case is indeed undefined behaviour. The post-decrement clearly subtracts one from a pointer to the beginning of an object, so the result does not point to an element of the same array, and by the definition of pointer arithmetic (§6.5.6/8, as cited in the OP) that's undefined behaviour. The fact that you never use the resulting pointer is irrelevant.

    What's wrong with:

    char *t = s + strlen(s);
    while (t > s) fputc(*--t, stdout);
    

    Interesting but irrelevant fact: The implementation of reverse iterators in the standard C++ library usually holds in the reverse iterator a pointer to one past the target element. This allows the reverse iterator to be used normally without ever involving a pointer to "one before the beginning" of the container, which would be UB, as above.

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