gcc bug or my bad?
Jul. 28th, 2015 01:30 pmI just wrote the following code:
This works when compiling as -O0, but with -O3 and size < 100 init_impl call is optimized out - printf is not called and array is not initalized.
The fix:
- if (size < 100) return init_impl(array, size);
+ if (size < 100) { init_impl(array, size); return; };
Is it a compiler bug or a C feature?
// very simplified:
int *init_impl(int *array, int size)
{
printf ("n = %i\n", n);
// initialize array
// return pointer to last element
return &array[size -1];
}
void init(int *array, int size)
{
if (size < 100) return init_impl(array, size);
// if size >= 100, initialize array as chunks of size 100
}
int main(int argc, char *argv[])
{
// malloc array
init (array, atoi(argv[1]));
process_array();
}
This works when compiling as -O0, but with -O3 and size < 100 init_impl call is optimized out - printf is not called and array is not initalized.
The fix:
- if (size < 100) return init_impl(array, size);
+ if (size < 100) { init_impl(array, size); return; };
Is it a compiler bug or a C feature?