C++的if语句使用逗号表达式 
转自    http://www.cnblogs.com/lingshaohu/archive/2011/10/31/2230085.html
Posted on 2011-10-31 12:21 mooner++ 阅读(73) 评论(0) 编辑 收藏  
1.C++的if语句使用逗号表达式,说明:
逗号表达式与加减乘除本质上是一样的, 它的求值是从左向右依次对表达式求值, 
整个表达式的结果取逗号表达式中最后一个表达的的结果, 如果非零, 就会使 if 成立!
 
2.实例说明:
(1)例子一:if (a!=b,b!=c,a!=c) 相当于:a!=b;b!=c;if (a!=c) 
再举个例子
(2)例子二:if (a=1,b=2,c>2)相当于a=1;b=2;if(c>2)也就是说,计算前两个逗号前的式子,而以最后一个式子做返回值标准。

解决方案 »

  1.   

    e1 , e2 The type and value of the expression are the type and value of e2; the result of evaluating e1 is discarded. The result is an l-value if the right operand is an l-value. Where the comma is normally used as a separator (for example in actual arguments to functions or aggregate initializers), the comma operator and its operands must be enclosed in parentheses.
      

  2.   

    问你个问题, int a = 10, b = 20;
    int i = a, b;
    int j = (a, b);
    i和j分别是多少? 为什么?
      

  3.   

    int a = 10, b = 20;
    int i = a, b;
    int j = (a, b);如果能编译过j是20,i是10,不过应该会报错的,b重定义
      

  4.   


    #include<stdio.h>
    int main()
    {
    int a = 10, b = 20;
    int i = a, b;
    int j = (a, b);
    printf("%d\n",j);
    return 0;
    }
    用VC++6.0编译后:
    --------------------Configuration: Haha - Win32 Debug--------------------
    Compiling...
    Haha.c
    C:\Documents and Settings\Administrator\桌面\Haha.c(35) : error C2086: 'b' : redefinition
    执行 cl.exe 时出错.Haha.obj - 1 error(s), 0 warning(s)