0

I am using C++ 11. I have a floating point number.

float some_float = 3.0;

Now I want to compile time check that this number is greater than some value. Say that I want to compile time assert that some_float is greater than 1.0. i am trying this:

static_assert(some_float > 1.0);

But, it errors out complaining,

error: static_assert expression is not an integral constant expression
static_assert(some_float > 1.0);
              ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Question:
what is wrong that I am doing?
How can I assert at compile time that some_float is set to something above 1.0?

TheWaterProgrammer
  • 7,055
  • 12
  • 70
  • 159
  • 1
    `static_assert` works on compile time only, it cannot check the value of `some_float `, because it doesn't really exist at that point. – DimChtz Oct 30 '17 at 23:09

1 Answers1

2

some_float must be constexpr

constexpr float some_float = 3.0;

If you define some_float simply as float, can be used in an assert(), that works runtime; not in a static_assert(), that is checked compile time.

Moreover: in C++11 it's required a string for an error message

static_assert ( some_float > 1.0f , "!" );  
//..................................^^^ error message
max66
  • 65,235
  • 10
  • 71
  • 111