+1 vote
98 views
#include<stdio.h>

int main()
{
int x, y = 7;
x = ++y + ++y + y--;
printf("%d\n", x);
return 0;
}


What is the output of this code snippet ?

A. 27

B. 26

C. 25

D. Compilation error

closed as a duplicate of: Undefined Behaviour in C

closed | 98 views
0

https://www.geeksforgeeks.org/sequence-points-in-c-set-1/

See here might it will help you to understand. It is a sequence point problem

0
A). 27

by Junior (549 points)
0
–2
Pre increamen have higher priority than all other operators so first they will increment after that binary operators will operate then after completion of that instruction i.e when control will transfer to next line ...post decrement operator will decrease y value ...

Y=>8 ==>9==>8...

9+9+9=27
0
@talha hashim

Then according to you,

if x = ++y + y-- ;

then it should be y => 8 ==> 7

and x = 8 + 8 = 16...right?

But it gives 15. Why?
+1

please avoid discussion on Undefined Behavior in C

+4
There are 10 kinds of people in world - one who understand undefined behaviour and one who doesn't :)
(y=7)

y--  -->y=7( y=y-1 will be perform at last)

++y -->y=y+1=7+1=8

(y=8, updated)

++y  -->y=8+1=9

(y=9, updated)

now x=y+y+y ----->(++y + ++y +y--)

x=9+9+9=27

now y=y-1 will be implemented

y=9-1=8

x=27,y=8
by (131 points)
0
@balaganesh

Then according to you,

if x = ++y + y-- ;

then it should be y => 8 ==> 7

and x = 8 + 8 = 16...right?

But it gives 15. Why?
0
After your question i have checked with various examples, I came to know that its depends upon the compiler.