2017-04-25 108 views
0
#include<iostream> 
using namespace std; 
int main() 
{ 
    if(for(int i=0;i<10;i++)if(i>6)break;) 
    cout<<"i went till 10";//execute if the if statement is true 
    else cout<<"i went till 6"; 
} 

如果它击中打破它应该去别的。 这是甚至可能的吗?如果有的话,在写这个问题时发生的错误感到抱歉。第二次尝试提问。我可以使用循环作为if语句条件语句吗?

我可以使用任何其他函数或语句来执行此类任务。

+0

当你在'6'之后总是'break'时,'i'会变成'10'吗?为什么不直接说'for(int i = 0; i <= 6; ++ i)'? – Galik

+0

这不是我想要实现的实际代码,它只是一个简单的例子来说明我想讨论什么问题 –

+0

“if”中的条件必须是一个值。 'for'不返回一个值,所以这是无效的。然而,还有其他方式可以像其他海报所表明的那样去做你想做的事情。 – Donnie

回答

3

没有,for语句是一个语句和的表达。条件表达式需要是一个表达式。

但是你当然可以,你在其他方面想要什么,甚至无需求助于goto。一种方法是再次检查循环条件,看看它是否失败(否则就必须打破圈外,给出一些假设):

int i; 

for(i=0; i<10; i++) 
    if(i>6) 
     break; 

if(i<10) // Loop condition still true, so we must have broken out 
    cout << "i went till 6"; 
else  // Loop condition not true, so we must have finished the loop 
    cout << "i went till 10"; 

如果这是不可能的,你可以使用一个变量来表示是否你是否打破了这个循环。或者你可以换环的功能及使用方法的返回值来表明是否爆发或成品:

bool broke_out_of_loop(void) { 
    for(int i=0; i<10; i++) 
     if(i>6) 
     return true; 
    return false; 
} 

void your_function(void) { 
    if(broke_out_of_loop())  
     cout << "i went till 6"; 
    else  
     cout << "i went till 10"; 
} 
+0

并不是真的,因为'''在'for'语句中声明,所以它不在其外部。 –

+0

@ el.pescado你是正确的,我感动的声明'外i'为目的... – skyking

+0

@skyking感谢名单,将尝试使用布尔函数 –

-1

不,你无法使用循环作为一个的if else条件语句。

+0

欢迎StackOverflow上到impliment。我注意到你有参加巡回演唱会的徽章。也许你应该重读关于如何回答的部分。 如果你想知道为什么你被低估了(不是由我,虽然我被诱惑):我猜downvoter的原因是你的答案没有帮助的性质。它基本上正确的事实并没有改变这一点。 – Yunnosch

0
if([&]{for(int i=0;i<10;i++)if(i>6)return false; return true;}()) 
    std::cout<<"i went till 10";//execute if the if statement is true 
    else std::cout<<"i went till 6"; 
} 

我不会建议这个构造,但上面的编译和做你想做的。