Search code examples
c++operator-precedence

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

Why is func_B getting called first ? i tried the same program in c# where func A gets called first.


Solution

  • C++ standard states that there's no guarantee about which one of the statements in function call parameters will be executed first. 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"