What is the purpose of -Wbad-function-cast, why does it only apply to a direct return value?

There is justification for the warning, but this does not answer the whole picture. For example, the following code triggers a warning:

(int)round(M_PI); 

but, on the other hand, the following code does not:

 double d; (int)(d = round(M_PI)); 

this is also not:

 (int)M_PI; 

the rationale was that you should not convert to int by simple casting, but you should use round , floor or a similar function. However, using round will still raise a warning, but as you can see above, when pointing to a constant or assigned variable, no.

So, if it’s bad to do from double to int , then why the warning is not triggered when writing (int)d or (int)M_PI ? How should warnings be avoided if you want to convert the return value? Is there a warning that will handle these dangerous conversions in a more proper / reasonable way?

+5
source share
1 answer

-Wbad-function-cast (C and Objective-C only)

Warn when a function call is passed to a mismatch type. For example, warn that calling a function that returns an integer type is cast to a pointer type.

As the name implies, -Wbad-function-cast only warns that you are calling function calls with an asymmetric type. He does not warn about all throws. This explains why you are not getting this warning for the last two examples:

You are right that it can be bad to drop from double to int , since you are potentially losing information. You can avoid the GCC warning by simply assigning the return value of the function to the appropriate type, and then say it later, as in the two examples that do not raise the warning.

Of course, the point of the warning is not to force you to write extra code to do the same. Even for functions that "return an integer value", such as round() , the return value may be too large to fit int . What you should do is check to make sure the value is safe for the first one. .

+4
source

Source: https://habr.com/ru/post/1242687/


All Articles