Jayy
Jayy

Reputation: 14728

C: simple code not working as expected (PIC micro)

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

Upvotes: 2

Views: 308

Answers (1)

Peter Alexander
Peter Alexander

Reputation: 54270

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

Upvotes: 4

Related Questions