Inspired by this question: How does *(&arr + 1) - arr give the length in elements of array arr?
The following code will calculate the length of an array, albeit invoking undefined behavior:
int arr[] = {5, 8, 1, 3, 6};
size_t len = *(&arr + 1) - &arr[0]; // len is 5
I believe, that by dereferencing the (&arr + 1) we are triggering undefined behavior. However, the only reason we are doing this is to immediately decay the result into int*
, pointing to one element after the last one in original array. Since we do not dereference this pointer, we are well in defined zone.
The question thus is following: is there a way to decay into int*
without dereferencing the undereferencable pointer and staying defined?
P.S. Mandatory disclaimer: yes, I can calculate the size of an array with sizeof
operator and division. This is not the point of the question.
EDIT: I am now less sure that the indirection itself is undefined. I have found http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#232 and from it looks it seems like there was an attempt to legalize the indirection per se, but I was not able to find any wording to this effect in actual standard.