Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of evaluation in C [closed]

The code below gives an answer (further below), that I do not understand.

#include <stdio.h>

int fA (int x) {
   int w = x;

   printf("%d", x);

   if (x > 4) 
      w += fA(x - 2);

   if (x > 2)
      w += fA(x - 4);

   printf("%d", x);
   return w;
}

int fB (int x) {

   if (x < 1) 
      return 1;

   int w = x;

   if (x > 2) 
      w = w * fB(x - 1);

   if (x > 1) 
      w= w + fA(x - 1);

   return w;
}

int main (void) {
   printf("\n %d %d \n", fA(6), fB(3));
   return 0;
}

it prints

112264004226
12 11

The question is why? In my opinion it should starts with 6. Thanks!

like image 275
user5857885 Avatar asked Jan 29 '16 15:01

user5857885


People also ask

What is the order of evaluation in C language?

Only the sequential-evaluation ( , ), logical-AND ( && ), logical-OR ( || ), conditional-expression ( ? : ), and function-call operators constitute sequence points, and therefore guarantee a particular order of evaluation for their operands.

Does C evaluate right to left?

There is no concept of left-to-right or right-to-left evaluation in C, which is not to be confused with left-to-right and right-to-left associativity of operators: the expression f1() + f2() + f3() is parsed as (f1() + f2()) + f3() due to left-to-right associativity of operator+, but the function call to f3 may be ...

What is order evaluation?

Order of evaluation refers to the operator precedence and associativity rules according to which mathematical expressions are evaluated.

What can be used to change the order of evaluation expression in C?

The compiler can evaluate operands and other subexpressions in any order, and may choose another order when the same expression is evaluated again.


2 Answers

There is no guarantee that parameters to a function will be evaluated in any particular order.

So when you call printf with fA(6) and fB(3) as parameters, the compiler is free to call either one before the other.

In this particular case, fB(3) was evaluated first. But if you use a different compiler, it might evaluate fA(6) first.

like image 101
dbush Avatar answered Nov 08 '22 04:11

dbush


There's no defined order. This depends on compiler, for example on:

# gcc -v
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-    dir=/usr/include/c++/4.2.1
Apple LLVM version 7.0.2 (clang-700.1.81)
Target: x86_64-apple-darwin14.5.0
Thread model: posix

this produces

640042261122
12 11

Moreover - the same compiler may decide order to be different for optimization

like image 44
Vasfed Avatar answered Nov 08 '22 05:11

Vasfed