Return values in while loops in functions.

  • Thread starter Thread starter torquerotates
  • Start date Start date
  • Tags Tags
    Functions Loops
Click For Summary
SUMMARY

The discussion centers on the behavior of return statements within a while loop in the context of a C++ function. The function check iterates through a vector v2 to determine if a specified item exists, returning true if found and false otherwise. The confusion arises from the understanding of control flow, specifically how the function exits upon encountering a return statement. It is established that the function exits immediately upon executing any return statement, thus the return false is only reached if the item is not found in the vector.

PREREQUISITES
  • Understanding of C++ programming language
  • Familiarity with control flow constructs (if statements, loops)
  • Knowledge of function return types and behavior
  • Basic understanding of vectors in C++
NEXT STEPS
  • Study C++ function return types and their implications
  • Learn about control flow in C++, focusing on loops and conditionals
  • Explore vector operations in C++, including iteration and searching
  • Examine debugging techniques for understanding function execution flow
USEFUL FOR

C++ programmers, computer science students, and anyone looking to deepen their understanding of function control flow and return statements in programming.

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 ·
Replies
3
Views
3K
  • · Replies 12 ·
Replies
12
Views
2K
  • · Replies 2 ·
Replies
2
Views
5K
  • · Replies 10 ·
Replies
10
Views
3K
  • · Replies 14 ·
Replies
14
Views
5K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 8 ·
Replies
8
Views
7K
  • · Replies 54 ·
2
Replies
54
Views
7K
  • · Replies 3 ·
Replies
3
Views
6K
  • · Replies 4 ·
Replies
4
Views
3K