Search code examples
cloopswhile-looppost-incrementpostfix-operator

behavior while loop in c programming


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


Solution

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