简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM