I am trying out "while" loop while reading C++ tutorial. Surprisingly the below loop always exits on 2nd iteration despite I gave negative integers.
while(int sz = get_size() && sz <= 0) ;
Below is the get_size() used.
int get_size() {
int a = 0;
cin >> a;
return a;
}
The purpose the break statement is to break out of a loop early. For example if the following code asks a use input a integer number x. If x is divisible by 5, the break statement is executed and this causes the exit from the loop.
break terminates the execution of a for or while loop. Statements in the loop after the break statement do not execute. In nested loops, break exits only from the loop in which it occurs.
The issue with your while loop not closing is because you have an embedded for loop in your code. What happens, is your code will enter the while loop, because while(test) will result in true . Then, your code will enter the for loop. Inside of your for loop, you have the code looping from 1-10.
When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop. It can be used to terminate a case in the switch statement (covered in the next chapter).
Your problem is that the statement is equivalent to
while(int sz = (get_size() && sz <= 0)) ;
Which would be undefined behavior for the first iteration because sz
is uninitalized.
A solution for this would be moving the declaration outside of the loop.
int sz;
while((sz = get_size()) && sz <= 0) ;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With