I’ve spent two full days now troubleshooting the following problem and I can’t figure it out for the life of me. The code seems so trivial that I feel like an idiot that it's not working. I have the following function with a switch/case block inside, which works just fine on my ATmega168. The function takes an argument row of type uint8_t and returns another uint8_t corresponding the selected case:
uint8_t lcd_get_offset(uint8_t row) { uint8_t row_offset = 0x00; // initialize to zero switch(row) { case 1 : row_offset = 0x01; break; case 2 : row_offset = 0x02; break; default : row_offset = 0x06; break; } return row_offset; }
Easy: the result of lcd_get_offset(1) is 1, as expected. The result of lcd_get_offset(2) is 2, as expected as well. The function returns 6 for any other value. No problemo.
If I simply add a third case to the switch statement, however, things go awry. Now, the following function with case 3 added returns 255 for function argument values of row=1, 2, or 3, which is wrong, but it still returns the default value of 6 for any other argument. All I did was add the third case, the function is otherwise exactly the same.
uint8_t lcd_get_offset(uint8_t row) { uint8_t row_offset = 0x00; // initialize to zero switch(row) { case 1 : row_offset = 0x01; break; case 2 : row_offset = 0x02; break; case 3 : // adding case 3 breaks things if input argument row =1, 2 or 3. row_offset = 0x03; break; default : row_offset = 0x06; break; } return row_offset; }
If I comment out the three lines starting with "case 3 :” then the function works just fine once again. Is there a fundamental issue with my switch/case statement? Otherwise, is this some kind of issue with the compiler? About a year ago I upgraded my toolchain to the latest version of Crosspack-AVR, with avr-gcc 4.8.1, but haven't had any issues until now. The second version of my function works fine and returns the expected values when compiled with gcc as a plain old non-AVR program on my computer, which makes me think the code itself is fine. Perhaps it's a bug in avr-gcc? Any insight is appreciated!
Thanks!