1

i am a beginner in c, and i am finding it difficult to understand the post and pre increment i have given my code below,i already compiled it in a turbo c++ compiler and i got output as a = 6 and b = 10 but since the post increment operator is used the output should be a = 6 and b = 11 ,why is it not happening?could someone explain it..

#include<stdio.h>    
int main()    
{
    int a=5,b;
    b = a++ + a;    
    printf("\na = %d and b = %d",a,b);    
    return 0;    
}
mathematician1975
  • 21,161
  • 6
  • 59
  • 101
prashanth
  • 69
  • 7

3 Answers3

7

The behaviour of a++ + a; is undefined in C. This is because the + is not a sequencing point and you're essentially attempting to increment and read a in the same expression.

So you can't guarantee a particular answer.

In order to understand prefix and postfix increments, use statements like b = a++; and b = ++a;

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
3

What happens in the following?

b = a++ + a; 

1) Is a incremented and its original value is then added to the original value of a?

2) Is a incremented and its original value is then added to the new value of a?

3) Is a on the right side fetched first and then added to the original value of an incremented a?

C allows any of theses approaches (and likely others) as this line of code lacks a sequence point which would define evaluation order. This lack of restriction allows compilers often to make optimized code. It comes at a cost as the approaches do not generate the same result when accessing a in the various ways above.

Therefore it is implementation defined behavior. Instead:

b = a++; 
b = b + a; 

or

b = a; 
b = b + a++; 
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
1

After int a = 5; the value of a is 5

b = a; // b is 5;

After int a = 5; the value of a++ is 5

b = a++; // b is 5

but the side effect of a++ is to increase the value of a. That increase can happen anytime between the last and next sequence points (basically the last and next semicolon).

So

/* ... */;
b = a++ + a;
#if 0
    /* side-effect */ 5 + 6
    5 /* side-effect */ + 6
    5 + /* side effect mixed with reading the value originating a strange value */ BOOM
    5 + 5 /* side effect */
#endif
pmg
  • 106,608
  • 13
  • 126
  • 198