简体   繁体   English

C ++函数调用中参数括号()的相关性

[英]Associativity of parameters parentheses () in C++ function call

Here is the sample code 这是示例代码

#include "stdafx.h"
#include <iostream>

int func_A();
int func_B();
void func_C(int a, int b);


int main()
{
    func_C(func_A(), func_B());
    return 0;
}

int func_A()
{
    std::cout << "in Function A" << std::endl;
    return 1;
}

int func_B()
{
    std::cout << "in Function B" << std::endl;
    return 2;
}

void func_C(int x, int y)
{
    std::cout << x + y;
}

Output: In Function B In Function A 3 输出:在功能B中在功能A 3中

Why is func_B getting called first ? 为什么首先调用func_B? i tried the same program in c# where func A gets called first. 我在c#中尝试了相同的程序,其中func A首先被调用。

C++ standard states that there's no guarantee about which one of the statements in function call parameters will be executed first. C ++标准规定,不能保证首先执行函数调用参数中的哪一个语句。 This is open to compiler's optimizer to decide. 这对编译器的优化器是可以决定的。 so you shouldn't rely on it. 所以你不应该依赖它。

Even in two different calls it can be different. 即使在两个不同的电话中,它也可能不同。 Furthermore, if you compile the code now and it works as you expected, there's no guarantee that it will work the same in next build or next version of that same compiler. 此外,如果您现在编译代码并且它按预期工作,则无法保证它在下一个版本或同一编译器的下一个版本中的工作方式相同。

But as Martin mentioned in the comment: "C# on the other hand, does mandate the order of evaluation" 但正如马丁在评论中提到的那样:“另一方面,C#确实要求评估的顺序”

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

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