3 ms·
Attempting to read s[i] when i is outside the bounds of the array is undefined behaviour, so the compiler is free to ignore this case. See example at http://en.
by ramchip 16y ago
Attempting to read s[i] when i is outside the bounds of the array is undefined behaviour, so the compiler is free to ignore this case. See example at http://en.wikipedia.org/wiki/Undefined_behavior#Examples_in_C.2FC.2B.2B http://en.wikipedia.org/wiki/Undefined_behavior#Examples_in_...
Certain pointer operations may result in undefined behavior:
int main()
{
int arr[4] = {0, 1, 2, 3};
int * p = arr + 5; // undefined behavior
}
In short, you can't assume that result will be placed after the array. What if result is optimized to a register? It actually sounds quite likely to me given the tight loop.
- afhof 16y agoWith C comes the pedantry int main(int argc, char ** argv) { int arr[4] = {0, 1, 2, 3}; int * p = arr + 5; // valid *p; // undefined behavior return 0; }
- mian2zi3 16y agoIf you're going to be pedantic, it is best to be right. I don't have a copy of the C standard here, but I do have a copy of the C++ standard. From 5.7 Additive Operators (discussing an expression of the form P+N, where P has pointer type and N has integral type): "If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined." That is, if either P or P+N don't point to the same array object, or one past the end of the array object, the result is undefined. Thus, int arr[4] = {0, 1, 2, 3}; ... arr + 4 ... // OK, points to one past the end of the array object ... arr + 5 ... // undefined I'm sure the C standard is the same.
- nitrogen 16y agoThis is one instance where C++ and C are, indeed, the same. However, the languages do have their differences, so I would caution those developers who don't tend to read standards not to assume that C and C++ will behave identically when given valid C code. Obviously, having referenced the C++ standard yourself, you are aware of such caveats. 6.5.6.8 from ISO/IEC 9899:201x draft of March 1, 2009: ...If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined....