-1
#include<stdio.h>

int main()
{ 
  int p=6;
  p=p++;
  p=p*10-20;
  printf("%d is p",p);
  return 0;
}

Here, If i compiled the program i will get the output 40. But if I tried to calculate output myself, I will get a wrong result i.e 50. In the line p=p++; I assigned the value 6 to p first and then incremented it to 7. Since the incremented value will also be assigned to p, then shouldnot we use the incremented one rather than the earlier value?

  • 2
    `p=p++` doesn't mean anything. If you want to increment `p` by 1, use `p = p + 1`, `p += 1`, `++p`, or `p++`. Don't try to use a combination like `p = p++` — you'll just confuse your compiler, yourself, and everyone else. – Steve Summit May 09 '22 at 01:55
  • This program outputs 50. – Laszlo May 09 '22 at 02:28
  • 1
    @Laszlo Not reliably, it doesn't. I tried it with two different, high-quality compilers. gcc gave 50. lldb gave a helpful compilation warning "multiple unsequenced modifications to 'p'", and the compiled code printed 40. Neither compiler is wrong. Your result of 50 is no more or less meaningful than any other. Please read some of the answers at the [linked duplicate](https://stackoverflow.com/questions/949433) if you have any doubts about this. – Steve Summit May 09 '22 at 03:33
  • First of all, it was a query of why it shows that behaviour and not about does it make sense or not. Secondly, p=p++ is an unspecified behavior which i got to know after posting the question, so it is dependent upon compiler. Thanks to steve summit for mentioning it. – Aagaman Sharma May 17 '22 at 08:36

0 Answers0