可能是一个非常简单的问题,但我无法找出原因。所有给定的代码都在同一个文件中。
这是数组之一的定义。它是在每个方法之外定义的。
unsigned char KEY_40_COMPARE_VALUES[] = {
85,102
,119,134
,147,158
,165,169
,169,165
,158,147
,134,119
,102,85
,67,50
,35,22
,11,4
,0,0
,4,11
,22,35
,50,67
};
这是代码:
unsigned char * getCompareValuesForIndex(char index)
{
if (index == 0)
{
return KEY_28_COMPARE_VALUES;
}
if (index == 1)
{
return KEY_30_COMPARE_VALUES;
}
if (index == 2)
{
return KEY_32_COMPARE_VALUES;
}
if (index == 3)
{
return KEY_33_COMPARE_VALUES;
}
if (index == 4)
{
return KEY_35_COMPARE_VALUES;
}
if (index == 5)
{
return KEY_37_COMPARE_VALUES;
}
if (index == 6)
{
return KEY_39_COMPARE_VALUES;
}
else
{
return KEY_40_COMPARE_VALUES;
}
}
这是我得到的编译错误:
conflicting types for 'getCompareValuesForIndex'
最佳答案
当您在提供函数原型(prototype)之前以及在文件中声明函数之前调用函数时,通常会发生这样的错误。在这种情况下,编译器假设
- 函数采用的任何参数均为
int
类型,并且 - 函数返回的值是
int
类型
本质上,该函数对于编译器来说是这样的:
int getCompareValuesForIndex(int index) { // <<= What compiler thinks
...
}
当编译器看到实际的声明时,它会发出错误。
要解决此问题,(1) 在调用之前提供函数原型(prototype),或者 (2) 将定义移到第一次使用函数之前。
注意:解决了这个问题后,请考虑通过添加静态数组来优化您的函数,如下所示:
unsigned char *KEY_COMPARE_VALUES[] = {
KEY_28_COMPARE_VALUES
, KEY_30_COMPARE_VALUES
, KEY_32_COMPARE_VALUES
, KEY_33_COMPARE_VALUES
, KEY_35_COMPARE_VALUES
, KEY_37_COMPARE_VALUES
, KEY_39_COMPARE_VALUES
};
现在你的函数可以像这样重写:
unsigned char * getCompareValuesForIndex(char index) {
return (index >=0 && index < 7) ? KEY_COMPARE_VALUES[index] : KEY_40_COMPARE_VALUES;
}
关于无法返回静态数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27782214/