Force C compilation error on simple arithmetic sanity check (addition, subtraction must match)

Viewed 26

Context

Imagine some code correctness depends on some value adding or subtracting to some other, so that at compilation time one can know if compilation should be aborted.

For example :

some.h
#define A 100
#define B 20
#define C 120

Imagine that code in some.c assumes that A+B == C, else it does not even make sense to compile it.

Wish

We wish compilation of some.c to fail if A+B is not equal to C.

some.cpp
#include "some.h"
#define CONTROL ((A)+(B)-(C))

something_that_cause_compilation_failure_if_argument_is_non_zero(CONTROL)

Non-solutions

This does not work because preprocessor does not do arithmetic, only string substitution:

#if CONTROL
#else
#error MISMATCH
#endif
1 Answers

This is solved by static asserts and is standard since C11 as indicated by Static assert in C

test.c

#define A 100
#define B 20
#define C 120

_Static_assert ( A+B == C, "A+B not equal to C");

int main()
{
    return 42;
}
gcc --std=c11 fail.c -o fail && echo SUCCESS

SUCCESS

If values are changed:

gcc --std=c11 fail.c -o fail

fail.c:14:1: error: static assertion failed: "A+B not equal to C"
   14 | _Static_assert ( A+B == C, "A+B not equal to C");
      | ^~~~~~~~~~~~~~
Related