条件表达式中的指针类型不匹配:编译器之间的行为不同

问题描述

示例代码:

int f1(char c){ return c; };
int f2(int i ){ return i; };

int main(void)
{
  return (1 ? f1 : f2)(0);
}

编译器之间的不同行为:

gcc (latest): gcc prog.c -Wall -Wextra -std=c89 -pedantic
prog.c: In function 'main':
prog.c:6:18: warning: pointer type mismatch in conditional expression
    6 |   return (1 ? f1 : f2)(0);
      |                  ^
prog.c:6:18: error: called object is not a function or function pointer
    6 |   return (1 ? f1 : f2)(0);
      |          ~~~~~~~~^~~~~
prog.c:7:1: warning: control reaches end of non-void function [-Wreturn-type]
    7 | }
      | ^
clang (latest): clang prog.c -Wall -Wextra -std=c89 -pedantic 
prog.c:6:13: warning: pointer type mismatch ('int (*)(char)' and 'int (*)(int)') [-Wpointer-type-mismatch]
  return (1 ? f1 : f2)(0);
            ^ ~~   ~~
prog.c:6:23: error: called object type 'void *' is not a function or function pointer
  return (1 ? f1 : f2)(0);
         ~~~~~~~~~~~~~^
1 warning and 1 error generated.
cl (latest): cl t1.c
t1.c(6): warning C4028: formal parameter 1 different from declaration
Microsoft (R) Incremental Linker Version 14.25.28611.0
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:t1.exe
t1.obj

问题:

  1. C标准怎么说?
  2. gcc和clang:为什么called object is not a function or function pointer?那是什么?
  3. cl给出警告,但编译代码。这种行为符合C标准吗?
  4. 为什么使用lang called object type 'void *',但为什么使用gcc called objectvoid *来自哪里?

解决方法

它将编译:

int f1(char c) { return c; }
int f2(int i)  { return i; }

int main()
{
  int (* f)(int);
  f = (1 ? f1 : f2);
  return f(0);
}

并且可以按预期工作,但是我真的没有很好的答案-仅在可能有助于您或其他人解决您问题的情况下发布此内容。 :)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...