c - 条件表达式: different behavior between compilers中的指针类型不匹配

标签 c compiler-errors compiler-warnings

样例代码:

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
问题:
  • C标准怎么说?
  • gcc和clang:为什么使用called object is not a function or function pointer?那这是什么?
  • cl发出警告,但编译代码。这种行为符合C标准吗?
  • 为什么使用lang called object type 'void *',但使用gcc called object?这个void *来自哪里?
  • 最佳答案

    这样编译:

    int f1(char c) { return c; }
    int f2(int i)  { return i; }
    
    int main()
    {
      int (* f)(int);
      f = (1 ? f1 : f2);
      return f(0);
    }
    
    并且可以按预期工作,但是我真的没有给您好的答案-仅在可能有助于您或其他人解决您问题的情况下发布此内容。 :)

    关于c - 条件表达式: different behavior between compilers中的指针类型不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64527885/

    相关文章:

    compiler-errors - 如何找出为什么xlC返回码非零?

    c - ARM 程序集 : Getting a string from STDIN

    c - 如何在 C 中获取源文件的完整路径?

    C++ boost库shared_memory_object undefined reference 'shm_open'

    c++ - 在 Mac OSX 中替代 --no-undefined

    java - 仅显示来自 eclipse 中某些文件夹的警告

    c - 函数的参数很少

    c - 使用 scanf 为结构赋值后程序停止

    xcode - 字符串在Swift中没有名为 'text'的成员错误

    java - 如何在 java 中创建自定义编译器警告?