简体   繁体   English

混淆静态int并在printf中调用它们

[英]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 . 从逻辑上讲,它应该打印1和2,但它打印2和1。 If you Un-Comment the comments and print the variables "first" and "second" , the problem is solved! 如果取消注释注释并打印变量“first”和“second”,问题就解决了! 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 . 函数调用参数的计算顺序是未指定的,即编译器可以在将返回值传递给printf之前以任意顺序进行两次func()调用。 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. 我认为在你的情况下,使用cdecl调用约定(许多C编译器用于x86架构),函数中的参数从右到左进行评估。

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中的最后一个首先被调用然后是前一个..这就是为什么它打印2然后1.尝试使用两个打印语句,如:printf(“First call:% d \\ n”个,FUNC()); printf("second call: %d\\n",func()); printf(“第二次调用:%d \\ n”,func());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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