Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between while(i=0) and while(i==0)

Tags:

c++

In my exam the following problem appeared in C++

Code:

int i, n;
int* A
cin >> n;
A = new int[n]
for(int i = 0; i < n; i++) cin >> A[i];

while(i = 0){
   cout << A[i] << endl;
   i--;
}
}

What will be the output? I think that it should go into indefinite loop!

like image 281
Frustrated Coder Avatar asked Mar 23 '11 08:03

Frustrated Coder


People also ask

What is the difference between while 0 and while 1?

Let us talk about the differences between while(1) and while(0) in C language. The while(1) acts as an infinite loop that runs continually until a break statement is explicitly issued. The while(0) loop means that the condition available to us will always be false.

Why is while 1 a forever loop?

The while(1) or while(any non-zero value) is used for infinite loop. There is no condition for while. As 1 or any non-zero value is present, then the condition is always true. So what are present inside the loop that will be executed forever.

How many times does the while 1 run?

A simple usage of while(1) can be in the Client-Server program. In the program, the server runs in an infinite while loop to receive the packets sent from the clients.

What is while n --> 0 in Java?

0 means "Check that n is not equal to zero before decrementing it; set n to n-1 after the check." This means that when n is equal to some number K before the loop, then the loop would repeat exactly K times.


1 Answers

while (i = 0) will assign the value 0 to i and then check whether the value of the expression (which is the value assigned, i.e. 0) is non-zero. In other words, it won't execute the body of the loop even once... it'll just set i to 0. It'll also raise a warning on any decent compiler, as it's a common typo.

Following the same logic, while (i = 1) would assign the value 1 to i and always execute the loop body... only a break (or exception) within the loop would terminate it.

(Many other languages don't have this issue as widely, as they require an expression of a boolean type for conditions such as while and if. Such languages still often have a problem with while (b = false) though.)

like image 196
Jon Skeet Avatar answered Sep 29 '22 21:09

Jon Skeet