0

I was solving some multiple choice C codes from a book. Two of the questions involve pre decrementing, post decrementing a char variable initialised at 0. The output for both these is very different. I dont understand whats going on there.

Code 1

char i=0;
do
{
    printf("%d ",i);
}while(i--);
return 0;

The output for this snippet is 0.

Code 2

char i=0;
do
{
    printf("%d ",i);
}while(--i);
return 0;

The output is for this one is
0,-1,-2,.....-128,127,126,......1 .

Can anyone explain why this is happening?

Kanchana Gore
  • 41
  • 1
  • 2

4 Answers4

2

At both code while loop checking i==0 or not. If i!=0it will keep going on.

At first code value of i initially 0. So after printing 0 it checks i==0 or not. if i==0 it will break the loop or keep going on by decrementing i. So in code 1 post decrementing used. check value first then decrements the value.

At second code value of i initially 0. So after printing 0 it decrements i then it checks if i==0 or not. it is pre decrement. decrement value first then check.

Here, i is char which size is 1 byte and range -128 to 127. So after decrementing value 0 to -1 it keep decrementing until it goes to 0 and exit the loop by printing 0,-1,...,-128,127...1 .

Sayed Sohan
  • 1,385
  • 16
  • 23
1
  • Initial value of i is 0.
  • In Code 1, first while check happens in which the value of i (= 0) is used and then i is decremented because it is postfix decrement. So it exits while after printing 0.
  • In Code 2, because it is prefix decrement, i is decremented first and its value (= -1) is used when the while check is performed. Here it exits after printing the entire range of values a signed char can hold because it becomes 0 at the end only.
P.W
  • 26,289
  • 6
  • 39
  • 76
1

Code 1

char i=0;
do
{
    printf("%d ",i);    // print o
}while(i--);           //check i = 0, means false, loop ends, then increment i
 return 0;

Code 2

char i=0;
do
{
    printf("%d ",i);     //print 0
}while(--i);             //decrement i, check i=-1, means true, next cycle, loop until i = 0 which means false
return 0;
Mike
  • 4,041
  • 6
  • 20
  • 37
1

Both i-- and --i are expressions. An expression is (part of) a statement that can yield a value. As per definition, the pre-increment version increments first, then yields the value. For the post-increment version it is the other way round.

This is completely independent of whether the expression is used in a while statement or elsewhere. However, when using such expressions, you need to be aware of operator precendence.

GermanNerd
  • 643
  • 5
  • 12