I learned from the accepted answer to
Make C floating point literals float (rather than double) and it's discussion,
GCC provides the compiler flag -fsingle-precision-constant
to force floating point literals to be single precision instead of the default double precision.
While this may have its pros and cons, is there a way (besides always using f
suffix) to ensure that code that is intended to be compiled with -fsingle-precision-constant
isn't falsely interpreted?
I came up with this,
int assert_float32_literals[1/(sizeof(float) == sizeof 1.0)];
which (kind of) works:
error: variably modified 'assert_float32_literals' at file scope
But is there a more explicit way with a clear error message?
C11 and above have support for static assertions with a message.
#include <assert.h>
static_assert(sizeof(float) == sizeof 1.0, "Float constants are not correct size");
Or use _Static_assert
if you don't want to include assert.h
.