Reputation: 17
#include <stdio.h>
int main() {
int i = -1;
int sum = 1000;
printf("\nThe value of sum to start is: %d", sum);
while (i <= 0) {
i = i - 1;
sum = sum + 1; }
if (sum == 0)
printf("\nSum is zero");
if (sum < 0)
printf("\nSum is less than zero");
if (sum > 0)
printf("\nSum is greater than zero");
printf("\n");
}
Can anyone explain why the result of sum is gonna be less than 0? and how will the while loop end?
Upvotes: 1
Views: 68
Reputation: 141554
This program causes undefined behaviour. After a while, sum
will reach the maximum possible value for an int
. Then sum + 1
causes undefined behaviour due to overflow in an arithmetic operation.
i
has a similar problem (if we fixed the sum
problem that is, which will overflow first).
Undefined behaviour means that anything can happen. The optimizer could spit out something that looks unrelated to the actual code, or the compiler could even refuse to compile the code (since the UB is guaranteed to happen in all code paths).
Example compilation by gcc -- the while
loop is replaced with an infinite loop that does nothing, since the optimizer removed some undefined code paths.
Upvotes: 3