55. Validate Frame Size

#include <iostream>
#include <cstdint>
using namespace std;
 
// Protocol frame used for sensor communication
struct Frame {
    uint16_t header;      // 2 bytes
    uint8_t  command;     // 1 byte
    uint8_t  length;      // 1 byte
    uint8_t  payload[6];  // 6 bytes
    uint16_t checksum;    // 2 bytes
};
 
// Validate compile-time size
static_assert(sizeof(Frame) == 12, "Frame size mismatch");
 
int main() {
    cout << "Frame OK";
    return 0;
}

Explanation & Logic Summary:

  • The struct must match the protocol exactly: 12 bytes total.
  • Any mistake in layout changes sizeof(Frame) and causes compilation failure.
  • static_assert enforces correctness at compile time, not runtime.
  • This prevents silent packet corruption and protocol mismatches.

Firmware Relevance & Real Embedded Context:

This problem mirrors real firmware practices:

  • UART packet formats
  • BLE advertisement frames
  • CAN message structures
  • Sensor communication packets
  • Bootloader frame formats
  • Diagnostic protocol frames

Static assertions protect against:

  • Accidental structural changes
  • Compiler padding issues
  • Protocol drift between teams
  • Hard-to-debug communication failures

This is a canonical embedded C++ safety pattern used in production firmware.

 

 

 

 

 

Loading...

Input

Expected Output

Frame OK