0

If i write the following:

for(int i=0; i<=1000; i++)
{
if(arr[1] == n){
   return true;
}
}

Will the loop break when the condition holds true and the return statement returns the value to the caller method? Or will the loop continue in anyway in that case (i.e when condition is true)?

1

"Will the loop break?" Technically speaking, no, it won't break. By using a return true statement, the entire function will immediately terminate and return a value of true to the calling code (or if in main, it will immediately terminate the program). My guess is that this is exactly what you want to do.

Understand that a break performs a different action. A break statement will actually cause the execution of the local for or while loop to terminate and continue processing with the code that immediately follows the loop. It will not cause the processing of the function to cease and return a value to the calling code.

So, while both a break statement and a return statement will cause loop processing to stop immediately, the return statement goes far beyond a break statement.

Because a lot of people may read this over time, it was important to state the difference.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

1

Yes, It will. By return keyword your program will be out of current function's scope. So it will be out of that loop.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .