So, in the Arduino world, what might the alternative behaviour be?
Whatever the compiler decides to do if it detects the violation. It is hard to predict how the gears in the optimizing compiler’s brain will mesh for code with undefined behavior. We’ve seen all kinds of weird results.
Do you have a program I could try which demonstrates the problem?
For Arduino IDE specifically? No, I didn’t have a chance to try it in Arduino IDE and its avr-gcc. Otherwise, the Net is full of examples that can be found by doing a search for “gcc strict overflow semantics”.
A simplest example might look as follows
for(int i = 0; i > 0; ++i)
This loop is obviously supposed to iterate until
i rolls over. However, compiled with AVR-GCC 4.6.4 the function becomes empty: Compiler Explorer (at all optimization levels above
-O0). The compiler detected the undefined behavior and decided to simply discard the whole loop. The optimization (and other) gcc settings for Arduino IDE might be different and might produce different result.
I also have this interesting example in my notebook, which also relies on compiler at compile time detecting overflow in signed arithmetic and generating “weird” code
/* Cycle in main performs only one iteration with -O2 and higher */
int N = 2;
/* When `N` is a file-scope variable, the compiler remains silent and generates
only one iteration of the cycle (the code outputs `1`). If `N` is made local
or an explicit constant is used in the cycle condition, a warning about
undefined behavior on the second iteration is issued by the compiler, but it
generates both iterations (the code outputs `2`) */
int ni = 0;
for (int i = 1; i <= N; i++)
arr[i] = i * 1073741824; /* Triggers signed overflow when `i` is greater than 1 */
Would be interesting to reproduce this in Arduino IDE. Of course, the constants will have to be updated, considering that Arduino
int is only 16 bits wide.