使用C中的逗号操作 [英] Using comma operator in c

查看:121
本文介绍了使用C中的逗号操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已阅读,逗号操作符用于分配前pression,右侧前pression提供给左值。

但为什么这个程序分配左侧前pression不使用时parenthesis.I正在使用的Turbo C编译器左值

  INT B = 2;
int类型的;
一个=(B + 2,b *表5); //打印10预期
A = B + 2,b *的5; //输出不使用括号4时

还有以下工作

  int类型的=(B + 2,B * 5);

这生成错误,我无法理解的原因。

  INT A = B + 2,B * 5; //错误


解决方案

由于运算符的precedence比 = <低/ code>之一,这...

A = B + 2,B * 5;

...实际上将评价为...

  A = B + 2;
B * 5;

使用 INT I = B + 2,B * 5; 是有点不同,因为逗号在声明语句不同的含义,分离彼此不同的声明。试想一下:

  int类型的= 3,B = 4;

您仍然有逗号这里,但现在它分隔两个变量赋值上声明。这就是编译器如何试图把该行从你的榜样 - 但未能从 B * 5 行(这是既不分配,也不声明)任何意义

现在, int类型的=(B + 2,B * 5)不同的是:你的分配的值 b + 2,b * 5 前pression给一个变量 A INT 。第一个子的前pression被丢弃,让你只需用 B * 5

I have read that comma operator is used to assign expression, and the right expression is supplied to lvalue.

But why does this program assign left expression to lvalue when not using parenthesis.I am using turbo c compiler

int b=2;
int a;
a=(b+2,b*5);  // prints 10 as expected
a=b+2,b*5;    // prints 4 when not using parenthesis

Also the following works

int a =(b+2,b*5);

And this generates error,I couldn't understand the reason.

int a =b+2,b*5;   // Error

解决方案

Because precedence of , operator is lower than of = one, this...

a=b+2,b*5;

... will actually be evaluated as...

a = b + 2;
b * 5;

With int i = b + 2, b * 5; is a bit different, because comma has different meaning in declaration statements, separating different declarations from each other. Consider this:

int a = 3, b = 4;

You still have comma here, but now it separates two variable assignment-on-declarations. And that's how the compiler attempts to treat that line from your example - but fails to get any meaning from b * 5 line (it's neither assignment nor declaration).

Now, int a = (b + 2, b * 5) is different: you assign a value of b + 2, b * 5 expression to a variable a of type int. The first sub-expression is discarded, leaving you just with b * 5.

这篇关于使用C中的逗号操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆