What is the purpose of gcc -Wbad-function-cast?

As the answer said here, I turned on -Wbad-function-cast to find out if the gcc behavior was bad in my code, and it appeared in this example:

 unsigned long n; // ... int crossover = (int)pow(n, .14); 

(here it is not so important that the crossover be int , it could be unsigned long , and the message would be the same).

This seems like a pretty ordinary and useful casting example. Why is this problematic? Otherwise, is there a reason for warning about this warning?

I usually like to set a lot of warnings, but I can't think about this use case. The code I'm working on is of great numerical value, and there are many times when things are passed from one type to another, as required to satisfy the various needs of the algorithms involved.

+6
source share
2 answers

The warning utility -Wbad-function-cast limited.

It is probably no coincidence that neither -Wall nor -Wextra allow this warning. Same as for C ++ (this is only C / Objective-C).

Your specific example does not use undefined behavior or the behavior defined by the implementation (see ISO C11, section 6.3.1.4). So this warning gives you zero benefits.

In contrast, if you try to rewrite your code to make -Wbad-function-cast happy, you simply add extra function calls that even recent GCC / Clang compilers do not use, t optimize with -O3 :

 #include <math.h> #include <fenv.h> int f(unsigned n) { int crossover = lrint(floor(pow(n, .14))); return crossover; } 

(a negative example warning is not issued with -Wbad-function-cast , but with extra function calls)

+1
source

You must take this warning seriously.

If you want to get an integer from a floating point result, this is a rounding operation that must be performed using one of the standard rounding functions, such as round . Doing this with a solid throw can lead to surprises: you usually lose the fractional part, and, for example, 2.76 can end as 2 with a whole truncation, just as 2.12 ends as 2 . Even if you want this behavior, you'd better specify it explicitly using the floor function. This will increase the readability and support of your code.

+5
source

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


All Articles