Similar annoying problems arise when people try to be clever with C strings, and read past the null. You can write optimisations which work, but they require care.
Similar annoying problems arise when people try to be clever with C strings, and read past the null. You can write optimisations which work, but they require care.
Is there a way to tell the compiler this? I've been trying with std::vector and std::array instead of raw pointer but without any luck. std::array also constrains you to static length.
"A declaration of a parameter as ''array of type'' shall be adjusted to ''qualified pointer to type'', where the type qualifiers (if any) are those specified within the [ and ] of the array type derivation. If the keyword static also appears within the [ and ] of the array type derivation, then for each call to the function, the value of the corresponding actual argument shall provide access to the first element of an array with at least as many elements as specified by the size expression."
According to this, the following syntax could be used for optimization
void foo(size_t n, int array[static n]) {...}
pointers to array could be used too void foo(size_t n, int (*array)[n])
{
printf("array %zu, *array %zu\n", sizeof(array), sizeof(*array));
}
foo( 10, null); // array 8, *array 40
foo(100, null); // array 8, *array 400This sort of optimization reasoning can result in quite surprising behavior: http://blog.llvm.org/2011/05/what-every-c-programmer-should-...
If I write a routine which walks an array one element at a time, in order, up to some max index N, and also stops early when it reaches some other condition (like an element equal to zero), then I am allowed to pass in memory which is only 3 elements long, and an N greater than 3, if I know that there is a zero in the first 3 elements. The function must not be optimized to read past the zero element, regardless of the N passed in, so removing the early exit would be an invalid optimization.
There's no undefined behavior in the above that justifies that optimization.