Ian D Ian D - 1 month ago 9
C Question

C type cast for typedef defined in preprocessor block

I am trying to fix this compiler warning:

warning C4244: '=' : conversion from 'double' to 'myRealVar', possible loss of data


myRealVar is defined in a preprocessor block:

#ifdef SINGLE_PRECISION
typedef float myRealVar;
#else
typedef double myRealVar;
#endif


The warning occurs on the line that basically looks like this:

someVar[a][b] = 1.0/sqrt(someVar[a][b]);


I have tried C-style type casting: (myRealVar) but this doesn't seem to resolve the warning. How should I properly resolve this issue?

Edit:
This did the trick. Thanks Weather Vane and Olaf. Not sure why my previous attempts at C-casting didn't working.

someVar[a][b] = (myRealVar)(1.0/sqrt(someVar[a][b]));

Answer

You need to cast the 1.0 as well as the return value from sqrt, to remove the warning. Both have the type double.

someVar[a][b] = (myRealVar)1.0 / (myRealVar)sqrt(someVar[a][b]);