</>EmbeddedInterview
← All problems · Drivers & Peripherals

Wrap-Safe Timeout Check

Easy

A 32-bit millisecond tick counter overflows every 49.7 days. Write bool timeout_expired(uint32_t now, uint32_t start, uint32_t timeout_ms) that returns true once at least timeout_ms have passed since start, and stays correct across the counter wrapping from 0xFFFFFFFF to 0.

Write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.

Compute the elapsed time first, using unsigned subtraction.

#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>

bool timeout_expired(uint32_t now, uint32_t start, uint32_t timeout_ms)
{
    return (uint32_t)(now - start) >= timeout_ms;
}

Unsigned arithmetic is modulo 2³², so now - start is the true elapsed time even if now has wrapped past zero, provided the real interval is shorter than 2³² ms. The buggy version fails because start + timeout_ms itself overflows to a small number, making the timeout expire immediately (or never).

The (uint32_t) cast matters on 8- and 16-bit targets where narrower types would be promoted to signed int. Linux uses time_after(a, b) macros on jiffies for exactly this reason.

solution.c
OutputPress Run to compile and test your code.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
    CHECK(!timeout_expired(1000, 900, 200));
    CHECK(timeout_expired(1100, 900, 200));
    CHECK(!timeout_expired(0xFFFFFFF0u, 0xFFFFFF00u, 0x200u));
    CHECK(!timeout_expired(0x00000050u, 0xFFFFFF00u, 0x200u));   /* wrapped, 0x150 elapsed */
    CHECK(timeout_expired(0x00000100u, 0xFFFFFF00u, 0x200u));    /* wrapped, 0x200 elapsed */
    puts(fails ? "Some tests failed" : "All tests passed");
    return fails != 0;
}