there seems to be something of regarding the range of some types. Here at signed int's
I tried on the Uno this
signed int b = 1;
while (b > 0) {
Serial.println(b, DEC);
b++;
}
Serial.println(b, DEC);
b--;
Serial.println(b, DEC);
and expected something like:
...
32765
32766
32767
-32768
32767
but got either this
...
32765
32766
32767
-32768
-32767
-32766
...
so it doesn't leave the loop even its clearly b < 0
or this
...
32765
32766
32767
32768
32769
....
which shouldn't be possible in an signed int since it can only hold from -32768 to 32767. A recompile sometimes toggles between those 2 symptoms.
Using
volatile signed int b;
works as expected.
Could this be a bug in the compiler? I doubt it's to be expected since the documentation states clearly
The Arduino takes care of dealing with negative numbers for you, so that arithmetic operations work transparently in the expected manner
Arduino IDE 1.8.0 on manjaro package version 1:1.8.0-3
I don't see how you get your 1111111111111111 (or -1).
But even if you where right with -1 it would still be < 0 so it should still leave the loop which it doesn't.
And again why does it work with volatile?
A c compiler is not require to behave in any particular way in the presence of integer overflow.
In particular, the compiler might optimize the loop to never check the actual value, since incrementing a positive integer will always be positive,right?
I guess it makes optimization easier, but I find the practice annoying...
Ok I can see the point optimizing the condition away but it doesn't even work if I add this in the loop if (b<0) break; but that could be optimized away with the same reason. Even if this is the first compiler I met which does this.
But why is (1000000000000000)2 sometimes (in my opinion correctly) -32768 but sometimes
+32768 counting onwards. This seems like a bigger problem then optimizing an condition away. 32768 (and more) shouldn't be possible at all, even if it's not overflowing correctly or undefined or random or whatever, it must be something between -32768 and 32767 because it's impossible to hold any other value in this datatype. Btw. with an unsigned char instead of int the condition doesn't get optimized away and works as expected.
Imho variables in registers don't respect their type correctly. Storing and loading back from RAM seems to fix it I guess. Or can someone explain how it is possible to hold a bigger value in a datatype than possible?
cool thanks.
Can't believe i couldn't find anything even tho it's right there at github oO
Since I don't see a solved option in this forum i leave it as is