In some embedded C code for the MC9S12C32 microcontroller, I have a circular queue (or circular buffer) implemented with a static byte array and two โpointersโ for the front and back of the queue, which are actually only indexes for the queue array.
// call unsigned chars bytes typedef unsigned char byte; byte trear = 0; // SCI transmit display buffer IN index byte tfront = 0; // SCI transmit display buffer OUT index byte tsize = 16; // size of transmit buffer byte tbuf[16]= {0};// SCI transmit display buffer
Note that trear is the actual index of the back element, but tfront is one less than the actual index of the front element (naturally, modulo 16, of course). For example, if my buffer contains โhiโ, it might look like this (where empty slots are garbage values):
_________________________________ | | |h|e|l|l|o| | | | | | | | | | ^ ^ front rear
When it's time to remove the byte from the queue, I do this:
// increment front index tfront++; // wrap front index if it exceeded bounds tfront %= tsize; // (A) // get character to transmit byte outputChar = tbuf[tfront];
All this works fine - at least my program did not detect errors associated with this fragment. However, when I compile this program, my compiler warns me about the line marked (A) in the above snippet, complaining:
Warning: C2705: Possible data loss
main.c line 402
Line 402 is line (A). I should note that I am not using gcc or the like; I compile in the Freescale IDE CodeWarrior IDE, which sometimes gave me some few hoax warnings. In an attempt to get rid of the warning, I rewrote the fragment above:
// increment front index mod tsize tfront = (tfront + 1 >= tsize) ? 0 : tfront + 1; // (B) // get character to transmit byte outputChar = tbuf[tfront];
However, my compiler still issues the same warning, this time about line (B) . Maybe the compiler tells me that in the statement (tfront + 1 >= tsize) , tfront may be 255 before execution and overflow. Of course, I know that this will not happen, but my compiler does not.
If so, why was the problem in line (A) ? Basically, I would like to know that the compiler is unhappy.
After entering my question, I solved it by changing tsize to the type of the variable to define a preprocessor (i.e. #define TSIZE 16 ). However, my question is still standing.
Some related questions:
unsigned overflow with module in C
module operator with unsigned characters