I have a following simple code:
#include <stdint.h>
#include <stdbool.h>
static uint8_t getStatus(void)
{
return 123u;
}
bool getError(void)
{
bool error = (bool)getStatus();
return error;
}
And I get a following warning from gcc:
error: cast from function call of type 'uint8_t {aka unsigned char}' to non-matching type '_Bool' [-Werror=bad-function-cast]
From gcc manual:
-Wbad-function-cast (C and Objective-C only) Warn whenever a function call is cast to a non-matching type. For example, warn if int malloc() is cast to anything *
So there are 3 interesting situation. Only 2 of them all allowed by gcc, but I don't see any potential difference between them.
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;
So I have 3 questions:
- Why I can't cast a result from getStatus() to bool.
- Why I need to explicity cast result from getStatus to uint8_t and after that I can cast to bool.
- How the Werror=bad-function-cast flag can help me to find (or avoid) an issue, and which kind of issue?