我可以将for循环用作if else条件语句吗?

时间:2017-04-25 05:08:00

标签: c++

#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";
}

如果它打破了它应该去其他地方。 这是否可能?对于写这个问题的错误,如果有的话,不好意思。第二次尝试提问。

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

3 个答案:

答案 0 :(得分:3)

不,for-statement是一个语句而不是一个表达式。条件表达式需要是一个表达式。

然而,您当然可以通过其他方式做您想做的事情,即使不必诉诸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";
}

答案 1 :(得分: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";
}

我不会建议这个结构,但上面编译并做你想要的。

答案 2 :(得分:-1)

不,你不能将for循环用作if else条件语句。

相关问题