Issue
I am writing a project in Visual Studio then I use GCC in order to compile it. Sometimes it causes some problems: This time I cannot use sqrtf function because VS accepts it however GCC does not. So I need to find some way (maybe mathematical approach to calculate square root) to find square root of some number in a way both GCC and VS will accept. To be more precise this is the line which causes a problem:
float x_f = circleRadius - sqrtf((float)((circleRadius * circleRadius) - (y * y)));
I need to find the square root of (circleRadius^2 - y^2)
Solution
std::sqrt
solves this problem:
#include <cmath>
auto foo(int circleRadius, int y) {
float x_f = circleRadius - std::sqrt((float)(circleRadius * circleRadius - y * y));
}
compiles for both msvc and gcc according to https://godbolt.org/z/g9MJH6
You should prefer std::sqrt
to sqrtf
in C++. It works with more types, i.e., you could write your function more generically. It also does not use hungarian notation.
Edit: If you do not care if the calculation returns a float or a double, you could omit the cast and write the following:
auto x_f = circleRadius - std::sqrt(circleRadius * circleRadius - y * y);
If you care that a float is used, you can use std::sqrtf
instead.
If you have to use a cast, you should generally prefer static_cast
to C-style casts. Reasons for this are listed here.
Answered By - Stefan Groth