私は次のことを試しました:
if(int i=6+4==10)
cout << "works!" << i;
if(int i=6+4,i==10)
cout << "doesn't even compile" << i;
最初のものは正常に動作しますが、2 番目のものはコンパイルされません。どうしてこれなの?
編集:最初のものは意図したとおりに機能しない可能性があることがわかりました。if スコープ内の i の値は、10 ではなく 1 になります (この質問に関するコメントの 1 つで指摘されているように)。
if ステートメント内で同時に変数を初期化して使用する方法はありますfor(int i=0;i<10;i++)
か? if((int i=6+4)==10)
if スコープ内の I の値が 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.