转换时条件表达式中的不兼容类型

Incompatible types in conditional expression when casting

我目前正在完成 K&R 练习,但有些事情困扰着我。

我有 qsort 函数声明:

void qsort(void *v[], int left, int right,
           int (*comp)(void *, void *));

按照书上的说法,我应该可以使用条件表达式来选择比较函数。我有两个:

int numcmp(char *s1, char *s2)

和 cstring 的

int strcmp(const char *s1, const char *s2);

调用看起来像:

qsort((void **)lineptr, 0, nlines - 1,
            (int(*)(void *, void *))(numeric ? numcmp : strcmp));

我的 MS VS 给我一个错误:

Error: operand types are incompatible

然而,当我这样做时:

qsort((void **)lineptr, 0, nlines - 1,
            (numeric ? (int(*)(void *, void *))numcmp : (int(*)(void *, void *))strcmp));

一切正常。

是这本书写错了,还是只是VS的思路应该怎么做?

您的错误是为您的自定义比较函数使用了错误的原型 numcmp
它应该指向 const:

int numcmp(char const *s1, const char *s2); // Showing both equivalent orders for const

条件运算符不能接受参数 2 和 3,因为参数 2 和 3 都不能隐式转换为其他类型,但您可以自然地预先将它们转换为相同类型。

在C标准(6.5.15条件运算符)中条件运算符的描述中写道:

3 One of the following shall hold for the second and third operands: — both operands are pointers to qualified or unqualified versions of compatible types;

兼容函数应具有兼容参数。

因为你的函数有指针作为参数,所以

2 For two pointer types to be compatible, both shall be identically qualified and both shall be pointers to compatible types.

然而这两个函数的参数并不完全相同。

因此编译器是正确的。