Why calling function with function pointer does not guarantee the calling order with printf in C

37 Views Asked by At

While I studying about C language, there is some strange situation about array of function pointer. This is a sample code.

#include <stdio.h>

int foo(int n) {
        printf("foo: %d\n", n);
        return 0;
}

int bar(int n) {
        printf("bar: %d\n", n);
        return 1;
}

int main() {
        int (*p[2])(int) = { foo, bar };
        printf("%d %d\n", p[0](10), p[1](20));
        return 0;
}

Intuitively, function foo called first and function bar called second, but it does not.

What I expect as a result,

foo: 10
bar: 20
0 1

However, actual output is

bar: 20
foo: 10
0 1

To analyze the result, I create the assembly file using gcc. In main function, the assembly code looks like below.

main:
    # codes ...
    leaq  foo(%rip), %rax
    movq  %rax, -48(%rbp)  ; p[0] = foo;
    leaq  bar(%rip), %rax
    movq  %rax, -40(%rbp)  ; p[1] = bar;
    
    movq  -40(%rbp), %rax
    movl  $10, %edi
    call  *%rax            ; p[1](10);

    movq  -48(%rbp), %rax
    movl  $20, %rdi
    call  *%rax            ; p[0](20);
    # codes ...

Why gcc compiles bar(p[1]) first and foo(p[2])? Why it does not work intuitively?

0

There are 0 best solutions below