0
#include <stdio.h>

int main(void) {
    int a,b,c,d;
    a=5;
    scanf("%d",&d);
    b=(++a)+(++a);
    printf("changed declared value = %d operated value = %d\n",a,b);
    c=(++d)+(++d);
    printf("changed input value= %d operated value= %d ",d,c);
    return 0;
}

variable a is assigned value 5 and d is given value 5 from user. Then same increment operation is performed but output is different. Can someone explain why this is happening. Tried both cases on same compiler.

output image

Gerhardh
  • 11,688
  • 4
  • 17
  • 39
  • 1
    Your code does not guarantee successful input from user, because you ignore the return value of scanf. – Yunnosch Sep 08 '22 at 05:58
  • 1
    Please include text output as formatted txt into your question. – Gerhardh Sep 08 '22 at 05:59
  • https://meta.stackoverflow.com/a/285557/7733418 which applies to all textual information. – Yunnosch Sep 08 '22 at 05:59
  • Please, please, *please*, **please** [look at the warnings emitted by your compiler](https://godbolt.org/z/T376Eb3WW). "warning: operation on 'a' may be undefined [-Wsequence-point] b=(++a)+(++a);" – AKX Sep 08 '22 at 06:00
  • The duplicate link explains why the result is generally undefined. Yet it is interesting why it is different here. The compiler might simply take the value `5` that it know for variable `a` and do optimized calculation while for `d` it must use the value from your input. – Gerhardh Sep 08 '22 at 06:02
  • @Gerhardh I accept your opinion, while I disagree. Also, your comment probably undermines OPs chance to really understand the concept of undefined behaviour. – Yunnosch Sep 08 '22 at 06:06

0 Answers0