Wolf
Wolf

Reputation: 10236

Compile-time check for -fsingle-precision-constant

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?

Upvotes: 1

Views: 83

Answers (1)

user694733
user694733

Reputation: 16047

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.

Upvotes: 4

Related Questions