gcc的-Wbad-function-cast的目的是什么? [英] What is the purpose of gcc's -Wbad-function-cast?
问题描述
-Wbad-function-cast
来查看我的代码是否有任何gcc可能捕获的不良行为,并且出现了这种情况例如: unsigned long n;
// ...
int crossover =(int)pow(n,.14);
(这里并不重要, crossover
是一个 int
;它可能是 unsigned long
,并且消息将是相同的)。
这看起来像是一个非常普通且有用的演员示例。为什么这是有问题的?否则,是否有理由继续打开此警告?
我通常会设置很多警告,但我无法将自己的想法包含在用例中为这一个。我正在使用的代码是数值很大的,并且有很多次,事情从一种类型转换到另一种类型,以满足所涉及算法的不同需求。
-Wbad-function-cast
警告的实用程序是有限的。 很可能, -Wall
和 -Wextra
都不会启用该警告。它不适用于C ++(仅限于C / Objective-C)。您的具体示例不利用未定义的行为或实现定义的行为(cf 。ISO C11,第6.3.1.4节)。因此,此警告不会给您带来任何好处。
相反,如果您尝试重写代码以使 -Wbad-function-cast
很高兴你添加了多余的函数调用,甚至最近 GCC / Clang编译器不会使用
-O3
:
#include< math.h>
#include< fenv.h>
int f(unsigned n)
{
int crossover = lrint(floor(pow(n,.14)));
返回交叉点;
(反面例子,没有发出警告 with -Wbad-function-cast
但是多余的函数调用)
As advised by an answer here, I turned on -Wbad-function-cast
to see if my code had any bad behavior gcc could catch, and it turned up this example:
unsigned long n;
// ...
int crossover = (int)pow(n, .14);
(it's not critical here that crossover
is an int
; it could be unsigned long
and the message would be the same).
This seems like a pretty ordinary and useful example of a cast. Why is this problematic? Otherwise, is there a reason to keep this warning turned on?
I generally like to set a lot of warnings, but I can't wrap my mind around the use case for this one. The code I'm working on is heavily numerical and there are lots of times that things are cast from one type to another as required to meet the varying needs of the algorithms involved.
The utility of the -Wbad-function-cast
warning is limited.
Likely, it is no coincidence that neither -Wall
nor -Wextra
enable that warning. As well as it is not available for C++ (it is C/Objective-C only).
Your concrete example doesn't exploit undefined behavior nor implementation defined behavior (cf. ISO C11, Section 6.3.1.4). Thus, this warning gives you zero benefits.
In contrast, if you try to rewrite your code to make -Wbad-function-cast
happy you just add superfluous function calls that even recent GCC/Clang compilers don't optimize away with -O3
:
#include <math.h>
#include <fenv.h>
int f(unsigned n)
{
int crossover = lrint(floor(pow(n, .14)));
return crossover;
}
(negative example, no warning emitted with -Wbad-function-cast
but superfluous function calls)
这篇关于gcc的-Wbad-function-cast的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!