I'm new to programming and I had a question for a project I'm working on.
So if I run this code, does the while loop exit after sending the string "world" to the terminal? Or would it exit before that code is ran?
while (conditionalStatement == false)
{
std::cout << "hello ";
conditionalStatement = true;
std::cout << "world\n";
}
Edit:
When I run the code above it sends hello world to terminal. However, I have another few lines of code that are giving me some different results. Not sure why.
My project is setup basically like this and when I run it, the string "we broke the loop!" Isn't being sent to the terminal when the user inputs 2.
bool something = false;
while (something == false)
{
std::cout << "choose 2 to break loop.\n";
int loopbreak;
std::cin >> loopbreak;
if (loopbreak == 1)
{
std::cout << "were looping!\n";
}
else if (loopbreak == 2)
{
something = true;
std::cout << "we broke the loop!\n";
}
}
//continue code
CodePudding user response:
The answer is yes. The condition is only checked at the start of each loop iteration. If you want to end loop execution early, you must execute a break
statement.