1

I think the best way to describe the problem is to actually show the output of this simple code: Image contains code and output

#include<stdio.h>
int main()
{
int a=5,b;

b=a-++a;
printf("%d %d",a,b);

return 0;
}

As you can see, the values returned are logically correct. ++a increases the value of a to 6. Then b=6-6=0.

However, when I take the value of 'a' as user input using scanf, the following happens: Image contains code and output

#include<stdio.h>
int main()
{
int a,b;
scanf("%d",&a);
b=a-++a;
printf("%d %d",a,b);

return 0;
}

Shouldn't the results be identical or am I missing something simple here?

Irtiza
  • 19
  • 2

1 Answers1

0

The form a - ++a has an undefined value because the order of executions of the argument of '-' is undefined.

In the first case the compiler knows the value of a so it can optimize the code and finally all is known at compile time, not in the second case.

The fact the value is not the same when computed at compile time or execution time is a consequence of the form a - ++a whose result is undefined.

bruno
  • 32,421
  • 7
  • 25
  • 37
  • execution of both codes on online compiler(ideone) gives the same output (6 0). what might be the reason? does it depend on compiler version or something else? – Vikram Kumar Jan 24 '19 at 09:31
  • 1
    @VikramKumar while the behavior is undefined it can change from a compiler to an other or between two versions of the same compiler – bruno Jan 24 '19 at 09:32
  • @Downvoter in what way can this answer be improved? – Bathsheba Jan 24 '19 at 09:58
  • 1
    @Bathsheba not mine dv but expanation is wrong. Order of execution does not matter. Only sequence points. So obvious one of the most frequent duplicates + partially wrong answer. Deserves DV (decided to DV too) – 0___________ Jan 24 '19 at 10:05
  • @P__J__: Your order of execution is a good point. I'll downvote too. I don't think that answer voting ought to be a function of question duplicate though, the correct course of action is to close / delete the question. – Bathsheba Jan 24 '19 at 10:07
  • @P__J__ Order of execution does matter, the behavior is undefined because the order is undefined, how can you say the reverse ? – bruno Jan 24 '19 at 10:10
  • @Bathsheba please explain me how the behavior can be undefined if the execution order is defined ? That has no sense – bruno Jan 24 '19 at 10:13
  • `a - ++a` contains no *sequencing points*. Essentially you don't know if the first `a` is the "before" or "after" value of `a`. The irony here of course is that the duplicate explains this well. – Bathsheba Jan 24 '19 at 10:14
  • @bruno: Sadly in this case that matters. The term "sequencing point" is the critical one here. It's not the same as execution order. – Bathsheba Jan 24 '19 at 10:21