search
Log In

Gate CS [closed]

1 vote
166 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
in Programming
closed by
166 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

2 Answers

–2 votes
Answer is A. 27
0
Can you please explain?
–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 :)
–3 votes
(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
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.

Related questions

0 votes
0 answers
1
93 views
Suppose, I have this program… #include <stdio.h> #include <stdlib.h> int *g(void) { int *px; px = (int*) malloc (sizeof(int)); *px = 10; return px; } int main() { int y=*g(); /* Doubt */ printf("%d",y); } Now, if I modify the line labelled as ‘Doubt’ as :- int y=g(), then in the output, I get a garbage value. I am unable to understand why. Can anyone please explain ?
asked Jan 16, 2019 in Programming the_bob 93 views
3 votes
5 answers
2
844 views
Consider the following C program. # include int main( ) { static int a[] = {10, 20, 30, 40, 50}; static int *p[] = {a, a+3, a+4, a+1, a+2}; int **ptr = p; ptr++; printf("%d%d", ptr - p, **ptr}; } The output of the program is _________
asked Sep 4, 2017 in Programming Utsav09 844 views
0 votes
2 answers
3
154 views
The following program fragment prints int i = 5; do { putchar(i+100); printf(“%d”, i--;) } while(i); i5h4g3f2el 14h3g2f1e0 An error message None of the above
asked Apr 1 in Programming Lakshman Patel RJIT 154 views
0 votes
2 answers
4
156 views
What will be the output of following? main() { Static int a = 3; Printf(“%d”,a--); If(a) main(); } $3$ $3\;2\;1$ $3\;3\;3$ Program will fall in continuous loop and print $3$
asked Apr 1 in Programming Lakshman Patel RJIT 156 views
...