三元表达式"? :"问号后面的两个操作数必须为同一类型吗?

树无影 2011-12-28 10:10:13

/************************************************************************/
/* 三元表达式"? :"问号后面的两个操作数必须为同一类型吗?
*/
/************************************************************************/

#include <stdio.h>
#include <string.h>


int main()
{
int c = 0;
int d = 0;

int a = c > d ? 3 : "as"; //怎么没有报错啊?

printf("%d\n", a);

return 0;
}

...全文
886 14 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
wizard_tiger 2011-12-28
  • 打赏
  • 举报
回复
LZ这个程序是否会输出"as"这个字符串的首地址呢?
那么就是这个地址被转化为int型赋值给a。
wizard_tiger 2011-12-28
  • 打赏
  • 举报
回复
LZ这个程序是否会输出"as"这个字符串的首地址呢?
那么就是这个地址被转化为int型赋值给a。
wizard_tiger 2011-12-28
  • 打赏
  • 举报
回复
LZ这个程序是否会输出"as"这个字符串的首地址呢?
那么就是这个地址被转化为int型赋值给a。
hldc 2011-12-28
  • 打赏
  • 举报
回复
我用Dev-c++有警告
10 d:\我的文档\t.c [Warning] pointer/integer type mismatch in conditional expression
10 d:\我的文档\t.c [Warning] initialization makes integer from pointer without a cast
鲤鱼 2011-12-28
  • 打赏
  • 举报
回复
把“as”的地址赋给a了
机智的呆呆 2011-12-28
  • 打赏
  • 举报
回复
C99中"as"类型为char[3]。
数组名除在sizeof & 以及初始化表达式中外都会隐式的转换成指针类型,这儿就是char* 。
显然第二个操作数3和第三个操作数木有满足Constraints。

ISO/IEC 9899:1999 (E)
6.5.15 Conditional operator
Constraints
2 The first operand shall have scalar type.
3 One of the following shall hold for the second and third operands:
— both operands have arithmetic type;
— both operands have the same structure or union type;
— both operands have void type;
— both operands are pointers to qualified or unqualified versions of compatible types;
— one operand is a pointer and the other is a null pointer constant; or
— one operand is a pointer to an object or incomplete type and the other is a pointer to a qualified or unqualified version of void.
hywink 2011-12-28
  • 打赏
  • 举报
回复
float a = 1==1 ? 1 : 2.0 ;
这样应该是没错的,你主帖里面的运行一下看看,int a存不下字符串"as"。
hywink 2011-12-28
  • 打赏
  • 举报
回复
后两个操作数的类型只要和a能匹配就行。
iamnobody 2011-12-28
  • 打赏
  • 举报
回复
[Quote=引用 7 楼 haotiantoping 的回复:]
我用VC没有报错
[/Quote]

珍爱生命,远离vc6.0
建鼎呓语 2011-12-28
  • 打赏
  • 举报
回复
不在于三元表达式问号后面的两个操作数的类型是否一致,
而在于三元表达式返回的那个操作数的类型和赋值号前面的变量是否匹配。

比如
char * sp;
int * ip;
void * vp = (1 == 1) ? sp : ip;
c_losed 2011-12-28
  • 打赏
  • 举报
回复
[Quote=引用 7 楼 haotiantoping 的回复:]

我用VC没有报错
[/Quote]
真爱生命 远离vc 6

6楼的报错是vs2008提示的
树无影 2011-12-28
  • 打赏
  • 举报
回复
我用VC没有报错
c_losed 2011-12-28
  • 打赏
  • 举报
回复
error C2446: ':' : no conversion from 'const char *' to 'int'
树无影 2011-12-28
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 wizard_tiger 的回复:]
LZ这个程序是否会输出"as"这个字符串的首地址呢?
那么就是这个地址被转化为int型赋值给a。
[/Quote]就是那个地址值给他了

70,020

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧