Return values in while loops in functions.

  • Thread starter Thread starter torquerotates
  • Start date Start date
  • Tags Tags
    Functions Loops
AI Thread Summary
The discussion revolves around understanding how return statements function within a while loop in a C++ function. The provided code checks if an item exists in a vector, returning true if found and false if the loop completes without finding the item. The confusion arises from the behavior of return statements; once a return is executed, the function exits immediately, which means the return false statement only executes if the item is not found after all iterations. The control flow indicates that if the if condition is not met, the loop continues until the end, leading to a return false if no match is found. Clarifying these points helps in grasping the flow of control and return values in functions.
torquerotates
Messages
207
Reaction score
0

Homework Statement

I'm just trying to interpert how the return statement works.

bool check(int item, vector<int>& v2)
{ int i = 0;
while (i < v2.size())
{ if (item == v2)
return true;
i++;
}return false;
}

Homework Equations


The Attempt at a Solution



I'm confused about the return parts of this problem. I does the return false even get excecuted? I thought that once a return statement is reached in a function, the function exits. Or do I have to wait until the last "true" return for the function to exit?
 
Physics news on Phys.org
Think about the control flow of the code. The return true follows an if statement, so what does that mean? If that if conditional doesn't evaluate to true, what happens?
 

Similar threads

Replies
3
Views
2K
Replies
12
Views
2K
Replies
2
Views
4K
Replies
10
Views
3K
Replies
14
Views
5K
Replies
2
Views
4K
Back
Top