是什么导致“警告:条件表达式中的指针/整数类型不匹配"? [英] What is causing "warning: pointer/integer type mismatch in conditional expression"?
问题描述
我有一个枚举,以及一个全部使用该枚举的宏定义和方法.我无法编译它.请考虑以下代码.
I have an enum, and a macro definition and a method that all use the enum. I can't get it to compile. Consider the following pieces of code.
typedef enum fruits_t
{
APPLE,
ORANGE,
BANANA
} fruits_t;
#define KEY_TO_VALUE(x) ((x == APPLE) ? 0 : \
(x == ORANGE) ? 1 : \
(x == BANANA) ? 2 : \
"Undefined")
static void foo(char fruit) {
if (fruit == KEY_TO_VALUE(APPLE)) {
/* do something */
}
}
这可以编译,但是我收到以下警告.
This compiles, but I get the following warnings.
warning: pointer/integer type mismatch in conditional expression
warning: comparison between pointer and integer
为什么?我对C非常陌生,因此,如果您能解释一些对经验丰富的C开发人员而言显而易见的事情,我将不胜感激.我大部分的编程知识都是基于Java的.
Why? I am very new to C, so if you could explain things that may seem obvious to an experienced C developer, I'd appreciate it. Most of my programming knowledge is Java based.
推荐答案
编译器试图找出程序中每个表达式的类型.
The compiler is trying to figure out the type of each expression in the program.
诸如x > 0 ? 5 : "no"
的表达式使编译器抓狂.如果x大于零,则类型为int
,但如果不大于0,则类型为const char *
.这是一个问题,因为没有从指针到int
的自动转换(反之亦然).因此,编译器会对此发出警告.
An expression such as x > 0 ? 5 : "no"
makes the compiler scratch its head. If x is greater than zero, the type is int
, but if it isn't then the type is const char *
. This is a problem, because there is no automatic conversion from pointer to int
(and vice versa). So the compiler warns about it.
解决方案是确保无论fruit
的值是什么,KEY_TO_VALUE
的值都具有单一类型.例如,可以使用诸如-1之类的特殊值来代替"Undefined"(由于它是文字字符串,其类型为const char *
).
The solution is to make sure that no matter what the value of fruit
is, the value of KEY_TO_VALUE
has a single type. For example, instead of "Undefined" (which is of type const char *
, because it is a literal string), you can use a special value such as -1.
此外,请注意,APPLE
是值为0的常数,ORANGE
是值为1的常数,而BANANA
是值为2的常数(这是enum
的工作方式).因此,您不需要KEY_TO_VALUE
,因为常量已经具有所需的值.您可以直接将fruit
与APPLE
直接进行比较:
Also, note that APPLE
is a constant with the value 0, ORANGE
is a constant with the value 1 and BANANA
is a constant with the value 2 (this is how enum
works). So you don't need KEY_TO_VALUE
, as the constants already have the desired values. You can simply compare fruit
to APPLE
directly:
if (fruit == APPLE) { ... }
这篇关于是什么导致“警告:条件表达式中的指针/整数类型不匹配"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!