Take the address of a one-past-the-end array element via subscript: legal by the C++ Standard or not?

后端 未结 13 1512
傲寒
傲寒 2020-11-22 06:34

I have seen it asserted several times now that the following code is not allowed by the C++ Standard:

int array[5];
int *array_begin = &array[0];
int *ar         


        
13条回答
  •  迷失自我
    2020-11-22 07:04

    I don't believe that it is illegal, but I do believe that the behaviour of &array[5] is undefined.

    • 5.2.1 [expr.sub] E1[E2] is identical (by definition) to *((E1)+(E2))

    • 5.3.1 [expr.unary.op] unary * operator ... the result is an lvalue referring to the object or function to which the expression points.

    At this point you have undefined behaviour because the expression ((E1)+(E2)) didn't actually point to an object and the standard does say what the result should be unless it does.

    • 1.3.12 [defns.undefined] Undefined behaviour may also be expected when this International Standard omits the description of any explicit definition of behaviour.

    As noted elsewhere, array + 5 and &array[0] + 5 are valid and well defined ways of obtaining a pointer one beyond the end of array.

提交回复
热议问题