int a=1; int b=2; int c=a++ + ++b + b++ + b-- + ++b; printf("%d",c); | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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??????

28th Feb 2020, 4:20 AM
Purvansh Parmar
Purvansh Parmar - avatar
2 Answers
+ 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..
28th Feb 2020, 5:01 AM
DishaAhuja
DishaAhuja - avatar
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 --.
28th Feb 2020, 12:39 PM
Rafik Abdelhak Nadir
Rafik Abdelhak Nadir - avatar