1

output in this case is 1

int main() {
    int i = 500;
    while( (i++) != 0 );
    printf("%d\n", i);
    return;
}

output in this case is 0

int main() {
    int i = 500;
    while( (i=i+1) != 0 );

    printf("%d\n", i);
    return;
}

I'm Not sure why get this different output in every case I mean why 1 in first case and 0 at second case

2
  • 1
    Undefined behavior is undefined. Commented Jan 7, 2022 at 12:00
  • OT: you should indent your code properly on order to make it readable. Commented Jan 7, 2022 at 13:07

1 Answer 1

1

For starters the both programs have undefined behavior. Instead of declaring the variable i as having the signed integer type int you should declare it as having the unsigned integer type unsigned int to make the programs correct.

This while loop

while( (i++) != 0 );

stops its iterations when the expression i++ is equal to 0. So when the variable i is equal to 0 the loop stops. But due to the postfix increment operator its value is incremented and becomes equal to 1.

According to the C Standard (6.5.2.4 Postfix increment and decrement operators)

2 The result of the postfix ++ operator is the value of the operand. As a side effect, the value of the operand object is incremented (that is, the value 1 of the appropriate type is added to it).

This while loop

while( (i=i+1) != 0 );

also stops its iterations when i is equal to 0 after the assignment i = i + 1.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.