int a=1; int b=2; int c=a++ + ++b + b++ + b-- + ++b; printf("%d",c); | SoloLearn: Learn to code for FREE!

0

int a=1; int b=2; int c=a++ + ++b + b++ + b-- + ++b; printf("%d",c);

Why the above code gives 15 as output??????

2/28/2020 4:20:43 AM

Purvansh Parmar

3 Answers

New Answer

+3

int a=1; initially int b=2; initially int c=a++ + ++b + b++ + b-- + ++b; | | | | | 1 3 3 4 4 First pre increment in b will make b to 3 Second post increment will make b to 3 Then the value of b will be increment due to post increment property and value of b become 4 and then value of b will decrement and increment at the same time and final value of b is 4 and adding all this will return 15. It's an compiler dependent thing whenever the increment decrement question putted on and their output differs as the compiler behavior and result in undefined behaviour of code on various platforms..

+1

cause it's the same as 1 + 3 + 3 + 4 + 4. Left to write. The ++ before increments the value first and then uses it (prefix). The ++ after increments after using the value (postfix) That is: a = 1; b = 2; c = a++ + ++b + b++ + b-- + ++b; //c = 1 (now a = 2) + (now b = 3) 3 + 3 (now b = 4) + 4 (now b = 3) + (now b = 4) 4; // or simply // c = 1 + 3 + 3 + 4 + 4

0

You probably know that a postfix operator use the operand befor changing its value (increment or decrement). And that a prefix operator first changes its operand before taking its value. For the example: a = 1; b = 2. a++, use a = 1 then change the value to a = 2. ++b changing value first to b = 3 then use it. b++ from previous increment use b = 3, then changing to b = 4. b-- from previous increment use b = 4 then change to b = 3. ++b from previous decrement b = 3 changing value first to b = 4 then use it. At last: c = 1 + 3 + 3 + 4 + 4 = 15 But this is undefined behaviour, when you run the programme you will get a warning. Because you are changing b value many times between sequence points, three through ++, and once through --.