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