-2

When I compile following code it gives different output in different environment.

int a=4;
a = ++a + ++a;
printf("%d",a);

compiling this in Dev-C++ gives 12 while in xcode LLVM compiler it gives 11 as output.

Also when I compile following code

int a=4;
a = ++a + ++a + ++a;
printf("%d",a);

it gives 19 in Dev-C++ and 18 in xcode LLVM compiler.

Can anyone explain me more about this?

Manish Agrawal
  • 10,958
  • 6
  • 44
  • 76
  • 3
    Aha..long time since saw one of these :) We cannot tell you because the behavior is Undefined behavior. – Alok Save Apr 01 '13 at 06:20
  • `++a + ++a` is purely compiler dependent operation. There is no surprise in it. – Jeyaram Apr 01 '13 at 06:21
  • I propose that there should be a separate tag for `a = ++a + a++` type questions; there are so many of them ;-) – anishsane Apr 01 '13 at 06:33
  • You may have set the record for the person with the highest rep to ask this bad question. – Jim Balter Apr 01 '13 at 07:19
  • @JimBalter Thanks for letting me know, anyway I search on Google and found nothing so ask this question on this community. If you feel this question is bad than its fine but i still want to research on that and want to come on conclusion. it doesn't matter if someone is down voting to it. – Manish Agrawal Apr 01 '13 at 10:27
  • There's more to knowing how to program than searching on Google ... you also need to be familiar with the basics of the language you're programming in. In this case you're dealing with sequence points ... google that and you'll get your answer. – Jim Balter Apr 01 '13 at 10:33
  • yes, I always strive to clear my basic while coding, I came across such situation and didn't know the answer so posted on this. And I also I dont know the exact word so might not be able to search through Google. – Manish Agrawal Apr 01 '13 at 11:05

1 Answers1

0

The following code:

a = ++a + ++a;

and

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

are both examples of Undefined Behaviour, so the result is dependent on compiler, platform etc.

Please look at "The C Programming Language" by K&R, Section 2.12

Randy Howard
  • 2,165
  • 16
  • 26
Alex
  • 9,891
  • 11
  • 53
  • 87