4...">

Grading Order in C

Below is the code (below) which 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; } 

he prints

112264004226
12 11

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

+5
source share
3 answers

There is no guarantee that the parameters for the function will be evaluated in any particular order.

Therefore, when you call printf with the parameters fA(6) and fB(3) as parameters, the compiler can call one of them before the other.

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

+5
source

There is no specific order. It depends on the compiler, for example:

 # 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 gives

640042261122
12 11

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

+3
source

Is this a mystery?

I assume you expect it to start at 6, because fA (6) comes first. But printf arguments are evaluated in reverse order (by my compiler, YMMV), so fB (3) is called first.

+1
source

Source: https://habr.com/ru/post/1241824/


All Articles