Dark Mode

303 views

6 votes

What will be the output of the following program?

struct s{ int i; struct s *p; }; struct s arr[4] = { 7, arr+3, 8, arr+2, 9, arr, 8, arr+1, }; struct s *ap[] = {arr+3, arr+2, arr+1, arr}; struct s **pp =ap; int main() { printf("%d ", ap[++pp[2]->i-6]->i++); printf("%d ", pp[1]++->p++->i); printf("%d", ++arr[2].p->i); }

- $9\; 10\; 9$
- $7 \;8\; 10$
- $7\; 8\; 9$
- None of these

7 votes

**Answer: B**

https://en.wikipedia.org/wiki/Sequence_point#Sequence_points_in_C_and_C++

Before a function is entered in a function call. The order in which the arguments are evaluated is not specified, but this sequence point means that all of their side effects are complete before the function is entered. In the expression

`f(i++) + g(j++) + h(k++)`

,`f`

is called with a parameter of the original value of`i`

, but`i`

is incremented before entering the body of`f`

. Similarly,`j`

and`k`

are updated before entering`g`

and`h`

respectively. However, it is not specified in which order`f()`

,`g()`

,`h()`

are executed, nor in which order`i`

,`j`

,`k`

are incremented. If the body of`f`

accesses the variables`j`

and`k`

, it might find both, neither, or just one of them to have been incremented. (The function call`f(a,b,c)`

isnota use of the comma operator; the order of evaluation for`a`

,`b`

, and`c`

is unspecified.)

7 | 8 | 9 | 8 |

arr + 3 | arr + 2 | arr + 0 | arr + 1 |

arr + 3 | arr + 2 | arr + 1 | arr + 0 |

Precedence ( [] = → = ++ post = . struct member access) > (++ pre) > (- subtraction, not unary minus) .

printf("%d ", ap[++pp[2]->i-6]->i++);

pp[2] = (arr + 1); (arr + 1) → i = 8; ++8 = 9; 9 – 6 = 3;

ap[3] = arr; arr → i = 7; 7++;

**Printed: 7**

**Side effects: **

8 | 9 | 9 | 8 |

arr + 3 | arr + 2 | arr + 0 | arr + 1 |

printf("%d ", pp[1]++->p++->i);

pp[1] = (arr + 2); (arr + 2)++; (arr + 2) → p = (arr + 0); (arr + 0)++; (arr + 0) → i = 8

**Printed: 8**

**Side effects: **

8 | 9 | 9 | 8 |

arr + 3 | arr + 2 | arr + 1 | arr + 1 |

arr + 3 | arr + 3 | arr + 1 | arr + 0 |

printf("%d", ++arr[2].p->i);

arr[2].p = (arr + 1); (arr + 1) → i = 9; ++9 = 10 (immediate side effect, pre increment)

**Printed: 10**

@Yuvraj Raghuvanshi Can you please tell me how 8 becomes 9 after the first printf statement where 7 is printed? How does the side effect works there?

0

preeti0448 8 changes to 9 even before it is printed, that’s because it’s **pre**-increment, immediate effect, “here” in case of **post-**increment the side effects would take effect after semicolon.

I quoted “here” because there are many other ways for a side effect to be in effect, like passed inside function, in between logical operators like &&, ||, inside while check etc.

0