-1

Assume i > 0 is true. Why is this expression:

while(i > 0) {
  printf("Hello \n);
  i--;
};

equal to this expression:

 while(i--) {
  printf("Hello \n");
};
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Tolis M.
  • 27
  • 9

2 Answers2

4

Firstly, this is not an expression. It's a while loop. Also, they're not equal. while(i--) is equivalent to while(i-- != 0), which checks for inequality, not greater than.

If i is greater or equal than 0 in the beginning, both snippets will behave the same way.

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416
-1

It is evident that you mean the equivalence of the loop executions. They are equivalent due to the fact that the variable i is not used in the body of the loop and provided that i is a positive number.

However the loops logically look the following way

while(i > 0) {
  printf("Hello \n);
  i--;
};

and

while( int temp = i; i -= 1; temp > 0 ) {
  printf("Hello \n");
};

Though the second construction of the while loop is not valid but it shows that the variable i will be changed in any case whether when the condition is false or before each iteration of the loop.

Consider the following demonstrative program and its output.

#include <stdio.h>

int main(void) 
{
    int i = 1;

    puts( "The first loop" );
    while ( i > 0 ) 
    {
        printf("%d: Hello\n", i );
        i--;
    }

    putchar( '\n' );

    i = 1;

    puts( "The second loop" );
    while ( i-- ) 
    {
        printf("%d: Hello\n", i );
    }

    putchar( '\n' );

    i = 0;

    while ( i > 0 ) 
    {
        printf("%d: Hello\n", i );
        i--;
    }

    printf( "After the first loop i = %d\n", i );

    putchar( '\n' );

    i = 0;

    while ( i-- ) 
    {
        printf("%d: Hello\n", i );
        i--;
    }

    printf( "After the second loop i = %d\n", i );

    return 0;
}

The program output is

The first loop
1: Hello

The second loop
0: Hello

After the first loop i = 0

After the second loop i = -1

Take into account that in the condition of the first loop there is checked whether the variable i is greater than 0 while in the condition of the second loop there is checked whether the variable i is not equal to 0. So the conditions for entering the bodies of the loop are different.

If i has an unsigned integer type or it is guaranteed that i can not be negative then the following loops would be fully equivalent

while(i > 0) {
  printf("Hello \n);
  i--;
};

and

while(i != 0) {
  printf("Hello \n);
  i--;
};
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335