问题描述
给定以下代码
#include <stdio.h>
typedef enum{
ISP_INPUT_NONE,ISP_INPUT_DOLBY
} UserStream_t;
int someFunc(const char * str) {
printf("%s",str);
return 0;
}
int main(int argc,char** arg)
{
int a = ISP_INPUT_NONE;
someFunc(ISP_INPUT_NONE);
someFunc(a);
return 0;
}
第二次调用会触发整数转换警告,但第一次不会。
gcc -Wall test.c
test.c: In function ‘main’:
test.c:17:14: warning: passing argument 1 of ‘someFunc’ makes pointer from integer without a cast [-Wint-conversion]
17 | someFunc(a);
| ^
| |
| int
test.c:8:27: note: expected ‘const char *’ but argument is of type ‘int’
8 | int someFunc(const char * str) {
| ~~~~~~~~~~~~~^~~
枚举是否会默默地转换为指针? 我认为 C 枚举被视为整数。 我希望第一个调用生成与第二个调用相同的警告。
解决方法
枚举是否会默默地转换为指针?
嗯,其中一些。 ISP_INPUT_NONE
为 0
,枚举值为 constant expressions,值为 0
is a null pointer 常量的常量表达式。将空指针常量转换为另一个指针是正常的。
如果 enum
值不是 0
(例如 someFunc(ISP_INPUT_DOLBY);
),仍会发出警告。
传递枚举而不是指针时如何触发整数转换警告
想法:
以 1 而不是 0 开始 enum
。
typedef enum {
ISP_INPUT_NONE = 1,ISP_INPUT_DOLBY
} UserStream_t;
使用结构并有转换错误。
typedef struct {
unsigned char val;
} UserStream_t;
static const UserStream_t ISP_INPUT_NONE = {0};
static const UserStream_t ISP_INPUT_DOLBY = {1};
以某种方式使用宏使 ISP_INPUT_NONE
不是常量表达式。
static int entity(int a) { return a; }
typedef enum{
ISP_INPUT_NONE,#define ISP_INPUT_NONE (entity(ISP_INPUT_NONE))
ISP_INPUT_DOLBY
} UserStream_t;
使用带有 clang
选项的 -Wnon-literal-null-conversion
编译器。
在 g++ 中有 -Wzero-as-null-pointer-constant
选项,但在 gcc 中 C 没有这样的选项。您也可以向 gcc 提出功能请求。