在if语句中使用逗号运算符

Bor*_*nth 0 c++ if-statement comma

我尝试了以下方法:

if(int i=6+4==10)
    cout << "works!" << i;

if(int i=6+4,i==10)
    cout << "doesn't even compile" << i;
Run Code Online (Sandbox Code Playgroud)

第一个工作正常,而第二个不编译.为什么是这样?

编辑:现在我知道第一个可能无法正常工作.if范围内的i值将为1,而不是10.(正如此问题的其中一条评论所指出的那样).

那么有没有办法在if语句中同时初始化和使用变量for(int i=0;i<10;i++)?这样你就可以产生类似if((int i=6+4)==10)(不会编译)的东西,其中if范围内的I值为10?我知道你可以在if语句之前声明并初始化我,但有没有办法在语句本身内执行此操作?

为了让你知道为什么我觉得这会有用.

 if(int v1=someObject1.getValue(), int v2=someObject2.getValue(), v1!=v2)
    {
        //v1 and v2 are visible in this scope 
        //and can be used for further calculation without the need to call
        //someObject1.getValue() und someObject2.getValue() again.
    }
    //if v1==v2 there is nothing to be done which is why v1 und v2
    //only need to be visible in the scope of the if.
Run Code Online (Sandbox Code Playgroud)

CB *_*ley 5

用作初始化表达式的表达式必须是赋值表达式,因此如果要使用逗号运算符,则必须将初始化程序括起来.

例如(不是你正在尝试的东西很有意义,6 + 4没有副作用,值被丢弃并在其自己的初始化程序中i == 10使用未初始化的值i.)

if (int i = (6 + 4, i == 10)) // behaviour is undefined
Run Code Online (Sandbox Code Playgroud)

你真的是这个意思吗?

int i = 6 + 4;
if (i == 10)
Run Code Online (Sandbox Code Playgroud)

当使用它的形式if声明一个新变量时,检查的条件总是转换为的初始化变量的值bool.如果希望条件是涉及新变量的表达式,则必须在if语句之前声明变量,并使用要测试的表达式作为条件.

例如

int i;
if ((i = 6 + 4) == 10)
Run Code Online (Sandbox Code Playgroud)