-1

When I do this -

int i = 4;
printf("\n %d", ++i + ++i);

I get 12 as the answer. But when I do this -

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

I get 11 as the answer. Why?

I have tried both the code.

The expected value is 11 but why it is getting 12 in the first code?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 4
    Possible duplicate of [Why are these constructs using pre and post-increment undefined behavior?](https://stackoverflow.com/questions/949433/why-are-these-constructs-using-pre-and-post-increment-undefined-behavior). Turn on warnings and you'll see "warning: multiple unsequenced modifications to 'i' [-Wunsequenced]". – ggorlen Sep 19 '19 at 16:13
  • 1
    The second code fragment has well-defined behavior and gets the correct answer. The first fragment has undefined behavior, ecause it tries to modify `i` twice between sequence points. Always use code like the second fragment. – Steve Summit Sep 19 '19 at 16:29
  • @ggorlen Unfortunately he's unlikely to see that warning, as compilers that can emit it are still rather rare. – Steve Summit Sep 19 '19 at 16:31
  • @SteveSummit Ah, good to know. I used repl.it to get this running clang version 7.0.0-3~ubuntu0.18.04.1. – ggorlen Sep 19 '19 at 17:05

1 Answers1

2

This code snippet

int i = 4;
printf("\n %d", ++i + ++i);

has undefined behavior because there is no sequence point between calculations of expressions ++i.

This code snippet

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

is well-formed. The variable a gets the value of i after increment. So its value becomes equal to 5. At the same time i is also equal to 5.

After this statement

b= ++i;

b and i are equal to 6. So the sum of a and b is equal to 11.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335