免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
12下一页
最近访问板块 发新帖
查看: 3904 | 回复: 17
打印 上一主题 下一主题

[C] 关于逗号操作符的一些问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-10-13 00:48 |只看该作者 |倒序浏览
题目如下:

int i = 1,2;
printf("%d\n",i);

问结果是什么。。。。

[ 本帖最后由 kiffa 于 2008-10-13 16:21 编辑 ]

论坛徽章:
0
2 [报告]
发表于 2008-10-13 02:41 |只看该作者
原帖由 kiffa 于 2008-10-13 00:48 发表
她学生物的,不过学校要求学C语言,刚才拿了题考我,结果我错了。。。。
题目如下:

int i = 1,2;
printf("%d\n",i);

问结果是什么。。。。

6.5.17  Comma operator
Syntax
1 expression:
assignment-expression
expression  , assignment-expression
Semantics
2      The  left  operand  of  a  comma  operator  is  evaluated  as  a  void  expression;  there  is  a
sequence point after its evaluation.  Then the right operand is evaluated; the result has its
type and value.95)   If an attempt is made to modify the result of a comma operator or to
access it after the next sequence point, the behavior is undefined.
3      EXAMPLE     As  indicated  by  the  syntax,  the  comma  operator  (as  described  in  this  subclause)  cannot
appear in contexts where a comma is used to separate items in a list (such as arguments to functions or lists
of initializers).  On the other hand, it can be used within a parenthesized expression or within the second
expression of a conditional operator in such contexts.  In the function call
f(a, (t=3, t+2), c)
the function has three arguments, the second of which has the value 5.
Forward references:  initialization (6.7..

论坛徽章:
0
3 [报告]
发表于 2008-10-13 03:02 |只看该作者
好像无法编译通过吧?

论坛徽章:
0
4 [报告]
发表于 2008-10-13 03:32 |只看该作者
我当初不知道编译不过,所以我答错了,2L已经给出解释了。

然后又这样。。。

int i;
i = 1,2;
printf("%d\n",i);

问结果。。。

居然都不睡觉的。。。。

论坛徽章:
0
5 [报告]
发表于 2008-10-13 08:13 |只看该作者
2?

论坛徽章:
0
6 [报告]
发表于 2008-10-13 08:20 |只看该作者
逗号表达方式, 最后一个.

论坛徽章:
0
7 [报告]
发表于 2008-10-13 08:47 |只看该作者
还真是编译通不过。。

逗号表达式好理解,但是第一个为什么编译出错呢?想不明白

[ 本帖最后由 雨过白鹭洲 于 2008-10-13 08:50 编辑 ]

论坛徽章:
0
8 [报告]
发表于 2008-10-13 14:05 |只看该作者
第2题答案是1.。。。。。不是2.。。。

论坛徽章:
0
9 [报告]
发表于 2008-10-13 14:12 |只看该作者
估计是优先级问题吧
i = 1, 2;被转换成了(i=1), 2

至于 int i = 1, 2为啥出错就不清楚了
猜测可能是因为 (int i = 1), 2是非法的
因为这一行是为了声明变量,但是2这个表达式并没有声明一个变量

论坛徽章:
0
10 [报告]
发表于 2008-10-13 14:13 |只看该作者
等于号优先级高于逗号,所以答案为1,如果有括号则是2
第一个,应该是变量定义的规则不允许,也就是2被当作了变量而不是右值

[ 本帖最后由 AiSa.C 于 2008-10-13 14:15 编辑 ]
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP