简体   繁体   中英

confusion about static int and calling them in printf

Please test this code and give me your answers :

#include <stdio.h>

int func() {
static int n = 0;
n++;
return n;
}

int main() {
    /*int first = func();
    int second = func();*/
    printf(" first call : %d \n second call : %d ",func(),func());
    return 0;
}

Logically it should print 1 and 2 but it is printing 2 and 1 . If you Un-Comment the comments and print the variables "first" and "second" , the problem is solved! What is happening?

thank you already!

The order in which a function call's arguments are evaluated is unspecified, ie, the compiler is free to make the two func() calls in any order before passing the return values to printf . If you first assign the results to variables, obviously you get to decide in which order they are used.

The order in which the parameters to a function are passed is not defined in the standard, and is determined by the calling convention used by the compiler. I think in your case, cdecl calling convention (which many C compilers use for x86 architecture) is used in which arguments in a function get evaluated from right to left.

because while calling the function it takes right associative.. ie, the last one in printf gets called first then the before one.. thats why it is printing 2 then 1. try using two print statements like: printf("First call: %d\\n",func()); printf("second call: %d\\n",func());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM