如何解决条件表达式中的指针类型不匹配:编译器之间的行为不同
示例代码:
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 *'
,但为什么使用gcccalled 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);
}
并且可以按预期工作,但是我真的没有很好的答案-仅在可能有助于您或其他人解决您问题的情况下发布此内容。 :)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。