Can we write Break or Continue statement outside of For loop?

 Posted by vishalneeraj-24503 on 11/29/2013 | Category: C# Interview questions | Views: 3048 | Points: 40
Answer:

No, we can not write Break or Continue statement outside of For loop.
It will give a compile-time error as

"No enclosing loop out of which to break or continue."

Because they are the part of For Loop.

So we must write Break or Continue statement inside of For loop.

For Ex:-

public void check_value(int index)

{
for (int i = 0; i < index; i++)
{
int value = 0;
if (i == 2)
{
value = i;
}
}
break;
}


Above function will not compile.
It will give error as

"No enclosing loop out of which to break or continue."

Break statement must be inside for loop. It is used for break current statement will exit the for loop.

For working with above function and successfully compile,make changes as place break inside for loop on the function as below:-

public void check_value(int index)

{
for (int i = 0; i < index; i++)
{
int value = 0;
if (i == 2)
{
value = i;
}
break;
}
}


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response