in Programming in C edited by
3,201 views
3 votes
3 votes

Consider the following $\text{C}$ program. Assume parameters to a function are evaluated from right to left.

#include <stdio.h>

int g( int p) { printf("%d", p); return p; }

int h(i nt q) { printf("%d", q); return q; }

void f (int x, int y) {

g(x);

h(y);

}

int main() {

f (g(10), h(20));

}

Which one of the following options is the CORRECT output of the above $\text{C}$ program?

  1. $20101020$
  2. $10202010$
  3. $20102010$
  4. $10201020$
in Programming in C edited by
by
3.2k views

2 Comments

edited by

https://wiki.sei.cmu.edu/confluence/display/c/EXP10-C.+Do+not+depend+on+the+order+of+evaluation+of+subexpressions+or+the+order+in+which+side+effects+take+place 

visit this website. It is clearly stated that order of parameter evaluation is undefined in C. Also see text from KandR C book. 

answer can be option D 10201020 also.

0
0

@ak474521 questions says to assume right to left evaluation

3
3

2 Answers

4 votes
4 votes

$\underline{\textbf{Let's understand diagrammatically}} :$

 

$\text{As its mentioned $\textbf{"parameters to a function are evaluated from right to left"}$}.$

$\text{So, h() will be evaluated first, and it will print 20 first then g() will be evaluated and it will print 10.}$

 

 $\text{Now as g() and h() both function will return 10 and 20 respectively, so now $\textbf{f(10, 20)}$ will be called and from there,}$

$\text{ then again g() and h() will be called and 10 and 20 will be printed respectively.}$  

$\newline$

$\boxed{ \color{Red}\underline{\textbf{Output}}  \color{Black}\textbf{ : 20 10 10 20} }$   $\text{(Option A)}$

$\newline$


$\newline$

$\underline{\textbf{NOTE}} :$

"The order of evaluation of the function designator, the actual arguments, and subexpressions within the actual

 arguments is Unspecified, but there is a sequence point before the actual call".

$\newline$

$\underline{\text{For example}}:$  

               $\boxed{ \text{ fun(A(), B(), C()) } }$  $\text{for this fun() we can't say order of evolution is always either from Right to Left }$

$\text{or Left to Right. Its totally Unspecified according to}$ ISO - C99 Standard.

$\newline$

$\text{The possible order of evolution of A(), B(), C() can be: }$ 

$\text{ A(), B(), C() }$

$\text{ A(), C(), B()  }$

$\text{ B(), A(), C() }$

$\text{ B(), C(), A() }$

$\text{ C(), A(), B() }$

$\text{C(), B(), A()}$

$\newline$

$\underline{\text{References}} :$

              1. Order of evaluation in C

              2. ISO/IEC 9899:1999 (Chapter 6.5)

edited by

3 Comments

cool wow

2
2

πŸ™πŸ˜„ @Priyam Garg

2
2
Excellent answer.
1
1
0 votes
0 votes
ans: A)20101020
Answer:

Related questions