我尝试了后续的使用逗号操作:在if语句
if(int i=6+4==10)
cout << "works!" << i;
if(int i=6+4,i==10)
cout << "doesn't even compile" << i;
精细的首部作品,而第二个不能编译。为什么是这样?
编辑:现在我知道,第一个可能无法正常工作,因为我打算。 if范围内的i的值将是1,而不是10.(正如在这个问题上的一个评论所指出的那样)。
那么有没有办法在if语句中同时初始化和使用一个变量,类似于for(int i=0;i<10;i++)
?所以你可以产生类似于if((int i=6+4)==10)
(它不会编译)的地方,其中if范围内的值是10? 我知道你可以在if语句之前声明和初始化I,但是在声明本身中有没有办法做到这一点?
给你一个想法,为什么我认为这将是有用的。
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.
你为什么想这样做?任何具体要求? – Nawaz 2012-07-21 12:38:38
你使用什么编译器?他们都不应该编译...编辑:语句收回。 – quasiverse 2012-07-21 12:38:42
我猜你不知道逗号操作符实际上做了什么。你想达到什么目的? – tenfour 2012-07-21 12:39:24