august 发表于 2007-9-11 11:35:45

关于if.....else

这问题想问好久了,但一直没问
具体的例子忘记了,但记得以前是这种情况
在一个FOR循环中,放入IF....ELSE..IF什么条件就进行, ELSE 就BREAK;
但是当IF的条件为假时,ELSE却是不能退出循环的,而且FOR会进进行到底,
为什么会这样的呢?只有一个IF才能用BREAK;退出程序吗?

coolpay64 发表于 2007-9-11 18:32:19

break是迴圈才有效,某記得的好像if中是不理會break的
所以應該昰沒關係的。。。

coolpay64 发表于 2007-9-11 18:37:45


#include <iostream>
using namespace std;
int main(){
    for(int i=0;i<5;i=0){
      if(1!=2){
            cout << "BAKA " ;
      }else{
            break;
      }
      cout << "kill me" << endl;
    }
    return 0;
}


例中for(int i=0;i<5;i=0)是一個不會停的loop
如果if , else一段被注解,程式會一直寫 kill me kill me....
加上後,由於1!=2 -> true 所以會一直寫BAKA kill me BAKA kill me ....
但改成1==2 ->false後,程式會行break,停止for loop,結果啥也沒寫出來
可見if 中的break對if是無效但對if所在的loop有效

august 发表于 2007-9-11 22:27:04

意思是说BREAK 只会对循环有效,而对IF..ELSE就无效吗?

上例还不是通过IF条件不成立,然后执行ELSE下的BREAK;?
所谓的IF不理会BREAK怎么理解呢...

Zelsazgh 发表于 2007-9-11 22:33:35

....他是指IF就没有意义了....
if(a&lt;=10)
{      break;
      i=i+1;
}
else
{
   ...
}
执行BREAK直接跳出IF.....整个IF就没有意义了...

coolpay64 发表于 2007-9-12 22:10:16

如何說。。。
就是break在那兒也好,只會脱離迴圈,不理會有多少個if包住

yish 发表于 2007-9-13 17:52:45

break 和 if没关系

kurai 发表于 2007-9-13 23:00:44

http://img.photobucket.com/albums/v391/Swablu-City/Photo/break.png

做了個Experiment:
在 i = 5 的時候, if 裡面 Break 之後的 cout &lt;&lt; &quot; skipped &quot; 並沒有執行, 且inter_flag亦沒有變成1, 即是break 把 for loop 和 if 都即時停止了。

coolpay64 发表于 2007-9-14 18:12:26

那不如做這樣的一個實驗

#include <iostream>
using namespace std;
int main(){
if(1==1){
break;
cout << "inside";
}
cout << "outside";
return 0;
}


會出現error: break statement not within loop or switch
即是說,break不會對 if有效

break 把 for loop 即時停止了,但不是if

kurai 发表于 2007-9-14 21:52:08

Break have broken the whole for, so everything, including the If, will cease instantly.
So the flag didnt turn 1
页: [1] 2 3
查看完整版本: 关于if.....else