0

Practice test review question for C course.

int c = f1(2,3) * f2(3,4) + f3(4,5);

What is the order of the function evaluation? Answer was compiler dependent. My question: Why doesn't it use the left to right associativity and precedence of the *,+ operators? I changed it to f1()+f2()*f3(), and placed puts("f1 now) type commands in each function for a quick test. The result was order f1,f2,f3, so it is clearly not using the operator associativity and precedence for evaluation order of the functions. I was pondering the consequences that the 3 functions set/manipulate 3 global variables, so the evaluation order would matter.

Other than, don't write code like this (It was a practice review question), I am confused why operator precedence/associativity does not dictate the order of the function evaluations. Thanks in advance.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
M. Fuller
  • 81
  • 1
  • 1
  • Answer: professional engineers don't care because of the explicit brackets that they put in to make the operation of the code clear, or because they don't use such expressions at all since a temp var and two lines makes stuff easier to debug. – Martin James Oct 16 '17 at 15:59
  • 1
    You write code like that only when the order doesn't matter. You can write `y = sin(x) + cos(x);` but would never do `y = create_file(x) + write_data(x) + close_file(x);`. It just doesn't make sense. – Bo Persson Oct 16 '17 at 18:21
  • @MartinJames but putting in extra parentheses doesn't change the order of evaluation, right? it seems that's the entire point of the thread of which this was marked as a duplicate. (besides, I'm going to be the person who says I stubbornly refuse to put in extra brackets, because avoiding them ensures I know the precedence/associativity rules. *waits for barrage of tomatoes*) – underscore_d Oct 16 '17 at 19:28
  • @underscore_d wheeeeeeeeee *>splat<* – Martin James Oct 18 '17 at 14:41

1 Answers1

4

Operator precedence and associativity don't determine the evaluation order. They only tell the compiler where to add parentheses. Precedence means that f() + g() * h() is parsed as f() + (g() * h()). And associativity means that f() + g() + h() is parsed as (f() + g()) + h(). But in all these cases (even when the parentheses are explicitly given), the functions can be called in any order.

interjay
  • 107,303
  • 21
  • 270
  • 254