The below example does not work as I expected (using ">" in the conditional) with GCC on an 8 bit machine, and neither on Linux 64 bit. If I make Timer_Secs and FutureTimeout_1Minute f.ex. 16 bits wide (int in those cases is 16 bits) it works as it should (using ">" in the conditional).
So, to get this to work for 8 bits with sign I seem to have to use "==" in the conditional.
{
// Example with 8-bit only as tested with GCC 3.2 on AVR ATmega 128
unsigned int Cnt1 = 0; // 16 bits (kind of system clock)
unsigned int Cnt2 = 0; // 16 bits (observer, see what happens)
signed char Timer_Secs = 0; // 8 bits with sign
signed char FutureTimeout_1Minute = 60; // 8 bits with sign
while (Cnt1 < 602)
{ // ##
if ((Timer_Secs - FutureTimeout_1Minute) == 0)
{
FutureTimeout_1Minute += 60; // Overflow/underflow allowed,
// so wraps and changes sign
Cnt2++;
} else {} // No code
Timer_Secs++;
Cnt1++;
}
// ##
// Cnt2 is 35 if > 0 above #define AFTER_F(a,b) ((a-b)>0)
// Cnt2 is 35 if >= 0 above #define AFTER_EQ_F(a,b) ((a-b)>=0)
// Cnt2 is 10 if == 0 above #define AFTER_ON_F(a,b) ((a-b)==0) **EXPECTED!**
}
The compare seems to involve some kind of sign conversion. I have not studied the assembly code for the different cases, since I thought this could be solved at code level.
- Why is this so?
- To me this looks plain wrong?
- Still I assume it's compiled like this by design?
- Is there some kind of type transfer or type decoration I could have done?
The context here is a blog note called "Know your timer's type" at: [blog]: http://www.teigfam.net/oyvind/home/technology/109-know-your-timers-type/
Disclaimer: this is a private blog with no money, ads, free things for me or etc. involved. Neither I nor anybody get anything from clicking on this url nor any of the urls in any of my blog notes.
It works as expected in Go, see blog note or http://play.golang.org/p/lH2SzZQEHG
It does not seem to work as expected in C++ either.