in Programming edited by
143 views
3 votes
3 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,
    10, arr+1,
};

struct s *ap[] = {arr+3, arr+2, arr+1, arr};
struct s **pp =ap;
int main()
{
    printf("%d", ap[pp[0]->p->i%2]->i++);
}
  1. $7$
  2. $10$
  3. $9$
  4. $8$
in Programming edited by
143 views

1 Answer

4 votes
4 votes

Answer: B

Similar to WQ8-Q1

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) is not a use of the comma operator; the order of evaluation for a, b, and c is unspecified.)

arr
7 8 9 10
arr + 3 arr + 2 arr + 0 arr + 1
ap
arr + 3 arr + 2 arr + 1 arr + 0

 

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


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

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

ap[0] = (arr + 3); (arr + 3) → i = 10; 10++;

Printed: 10

Side effects:

arr
7 8 9 11
arr + 3 arr + 2 arr + 0 arr + 1
Answer:

Related questions