Simvik

Take the side effects out of the conditions

Code that reads a FIFO inside && conditions and ignores return values: make each read explicit. A medium embedded C problem (MISRA C on a real project), run…

medium · MISRA C on a real project · misra · coding-standards · side-effects · short-circuit · error-handling

read_command takes a 3-byte command from a receive FIFO: a header byte 0xA5, an opcode, and an argument. It returns true and fills in *opcode and *arg for a good command.

  • Empty FIFO: return false; nothing is logged.
  • The first byte is not 0xA5: log ERR_BAD_HEADER and return false. Only that one byte is consumed.
  • The header is right but the opcode or the argument is missing: log ERR_TRUNCATED and return false.

The code below does this, but the MISRA checker rejects it. Rule 13.5 forbids a call with side effects on the right-hand side of && or ||: whether a byte is consumed should never depend on short-circuit evaluation. Rule 17.7 requires every returned value to be used (if log_error's result really is not needed, say so with a (void) cast). Rules 14.4 (Boolean conditions) and 15.6 (braces) are checked too.

Rewrite it so that the checker reports nothing and it consumes exactly the same bytes as before.

Starter code

bool read_command(uint8_t *opcode, uint8_t *arg) {
  uint8_t header;
  if (!fifo_pop(&header)) return false;
  if (header != 0xA5) {
    log_error(ERR_BAD_HEADER);
    return false;
  }
  if (fifo_pop(opcode) && fifo_pop(arg)) return true;
  log_error(ERR_TRUNCATED);
  return false;
}

Example tests

A good command

const uint8_t bytes[] = { 0xA5, 0x10, 0x7F, 0xA5 };
load(bytes, 4);
take();

Expected output:

command 10 7F, 1 byte(s) left

A wrong header consumes one byte

const uint8_t bytes[] = { 0x00, 0xA5, 0x20, 0x01 };
load(bytes, 4);
take();
take();

Expected output:

  logged error 1
no command, 3 byte(s) left
command 20 01, 0 byte(s) left

Learn it first

  • MISRA C on a real project · Guidelines and their categories, the rules that change how you write, deviations, and compliance claims.

More MISRA C on a real project problems