Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While loop ends prematurely

Tags:

c++

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;
}
like image 741
modeller Avatar asked Jun 20 '14 22:06

modeller


People also ask

Which statement is used to terminate loop early?

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.

What does a break do in a while 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.

Why does while loop not stop?

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.

Why break statement is used in while or for loop?

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).


1 Answers

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) ;
like image 117
Dani Avatar answered Oct 13 '22 21:10

Dani