Letting the compiler know I am passing positive value in the sqrt - C++ [closed]

StackOverflow https://stackoverflow.com/questions/14194201

  •  13-01-2022
  •  | 
  •  

Question

I have this

return sqrt(a-b);

and I know that a is greater than b. How can I let the compiler know?

Was it helpful?

Solution

Compiler does not care. From "man sqrt" on Linux:

The sqrt() function returns the non-negative square root of x. It fails and sets errno to EDOM, if x is negative.

If you want compilation to fail if a-b is either not a compile time constant or is a negative compile time constant you can use static_assert or BOOST_STATIC_ASSERT, whichever is available in your environment:

static_assert(a - b > 0.0, "a must be > b");
return sqrt(a - b);

OTHER TIPS

Just write it as it is. The compiler doesn't need to know this information.
sqrt is designed to handle the condition where argument is -ve.
If the argument is negative, the global variable errno will be set to value EDOM.

If you write if !(a > b) return 0; on the previous line, then the compiler can in principle deduce that a > b at your line. Whether this knowledge makes any difference is of course entirely compiler-dependent.

Also, whether this is any use to you depends what difference you think it might make. If you're hoping to provide an optimization hint, then it probably doesn't help since the test will still be performed. You need to hint in some compiler-specific way (assuming your compiler provides a way). I haven't checked this, but for example on GCC you'd hope that if you do:

if (a > b) {
    return sqrt(a-b);
} else {
    __builtin_unreachable();
}

then the optimizer will (a) know that a > b when it calls sqrt and (b) not perform the a > b test, since it knows only one result is possible.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top