2

This line isn't working as expected:

uartPushPos = (uartPushPos + 1) % UART_TX_BUFF_LENGTH;

However this below, which in theory does the same, does work:

//if (uartPushPos == UART_TX_BUFF_LENGTH - 1){
if (uartPushPos >= UART_TX_BUFF_LENGTH - 1){
    uartPushPos = 0;
} else {
    uartPushPos++;
}

UartPopPos is type char, and UART_TX_BUFF_LENGTH is a preprocessor variable set to 16.

Why does the second code segment work, but not the first?

If it makes much of a difference, I'm using the SourceBoost BoostC compiler for the PIC microcontroller 16f.

Thanks

Jodes
  • 14,118
  • 26
  • 97
  • 156
  • 1
    In what way are you getting unexpected results with the first option? – Paul W Jun 26 '11 at 13:55
  • 1
    Is there a flag, such as the `-S` flag for gcc, that lets you have a look at the compiled assembler code? I think that would help you. – André Laszlo Jun 26 '11 at 13:56
  • All I know is it's not working as expected, I can't get my head round what's actually happening, perhaps I should some how isolate the code segment to test it properly, I was just hoping there was an obvious answer I'd missed! – Jodes Jun 26 '11 at 13:59

1 Answers1

4

They are different if uartPushPos is less than 0, or if it is more than or equal to UART_TX_BUFF_LENGTH.

See also Mod of negative number is melting my brain

Community
  • 1
  • 1
Peter Alexander
  • 53,344
  • 14
  • 119
  • 168
  • Also, the second snippet wouldn't work if `uartPushPos > UART_TX_BUFF_LENGTH - 1`. – André Laszlo Jun 26 '11 at 14:00
  • @Andre Laszlo: I mentioned that :) – Peter Alexander Jun 26 '11 at 14:02
  • Haha, sorry. Well, proper initialization is your friend I guess. And reading stuff before you comment... – André Laszlo Jun 26 '11 at 14:04
  • I've commented out the if statement for a new one so they should now be equivalent. (It didn't matter though, since the code with the if statement was the working one, not the modulo line). uartPushPos is a char so cannot be negative. There's still a difference some how, – Jodes Jun 26 '11 at 14:12
  • 1
    @Jodes: A char can be negative unless you configure your compiler to treat chars as unsigned (I know several PIC compilers where you can do this). Use `unsigned char` if you only want positive integers. – slebetman Jun 26 '11 at 14:16
  • The classic solution btw is to first add the bufferlength, and only then do the mod so (x+bufferlength+1) % bufferlength. Of course this only fixes the case where x >-bufferlength, but usually fixing the case -1 is enough. – Marco van de Voort Oct 15 '11 at 15:27