C++ c此代码控制语句如何工作

C++ c此代码控制语句如何工作,c++,if-statement,C++,If Statement,我尝试了这个程序,但它没有给出任何输出 int i=1,j=2,k=3; if(i>j) if(i>k) (this will not get executed) cout<<"hello"; (but this should get executed right) else cout<<"hai"; inti=1,j=2,k=3; 如果(i>j) 如果(i>k)(这将不会执行)

我尝试了这个程序,但它没有给出任何输出

  int i=1,j=2,k=3;
    if(i>j)
       if(i>k)    (this will not get executed)
        cout<<"hello";   (but this should get executed right)
     else
        cout<<"hai";
inti=1,j=2,k=3;
如果(i>j)
如果(i>k)(这将不会执行)

您编写的代码与此等效

int i=1,j=2,k=3;
if(i>j) // false
{
    if(i>k) // not evaluated, but would also be false
    {
        cout<<"hello";
    }
    else
    {
        cout<<"hai";
    }
}
inti=1,j=2,k=3;
if(i>j)//false
{
if(i>k)//未计算,但也将为false
{
库特

这既不是Java也不是C。
coutThe-else被绑定到最里面的if。如果你想将它绑定到最外面的if/coutt,请在内部if/coutt的外面用大括号括起来。这就是为什么你要使用括号。即使你在if或else部分只有一条语句要执行,也建议使用括号。使用括号可以让你的生活更轻松。
int i=1,j=2,k=3;
if(i>j) // false
{
    if(i>k) // not evaluated, but would also be false
    {
        cout<<"hello";
    }
}
else
{
    cout<<"hai"; // this is now executed
}
1. if(i>j)
2.    if(i>k)    (this will not get executed)
3.        cout<<"hello";   (but this should get executed right)
if (x)    // 1
    if(y) // 2
        ;
    else  // belongs to 2, because it's nearer
        ;
else      // belongs to 1
    ;

if (x) {   // 1
    if(y)  // 2
        ;
} else     // belongs to 1, because 2 is not a direct predecessor