为什么需要强制转换两次以使-Werror = Bad-function-cast的警告静音

问题描述 投票:-1回答:1

我有以下简单代码:

#include <stdint.h>
#include <stdbool.h>

static uint8_t getStatus(void) 
{
    return 123u;
}

bool getError(void)
{

    bool error =  (bool)getStatus();
    return error;
}

而且我从gcc收到以下警告:

error: cast from function call of type 'uint8_t {aka unsigned char}' to non-matching type '_Bool' [-Werror=bad-function-cast]

从gcc手册:

-Wbad-function-cast(仅适用于C和Objective-C)在将函数调用强制转换为不匹配的类型时发出警告。例如,如果将int malloc()强制转换为任何值,则发出警告*

所以有3种有趣的情况。它们中只有2个被gcc允许,但是我看不出它们之间有任何潜在的区别。

bool error =  getStatus(); //THIS IS OK
return error;


bool error = (bool)getStatus(); //THIS IS BAD
return error;


bool error =  (bool)(uint8_t)getStatus(); //THIS IS OK!
return error;

所以我有3个问题:

  1. 为什么我不能将getStatus()的结果强制转换为bool。
  2. 为什么我需要将结果从getStatus显式转换为uint8_t,然后才能转换为bool。
  3. 此标志如何帮助我发现(或避免)问题,以及哪种问题?
c casting gcc-warning
1个回答
0
投票

存在的原因在文本中给出:在C89中,但在以后的C版本中却没有,可以使用没有给出明确定义的函数。然后,例如,如果您没有#include <stdlb.h>,则假定它的声明为int malloc()。如果您then

© www.soinside.com 2019 - 2024. All rights reserved.