Search code examples
c++csemanticsmultiplatform

C/C++ - evaluation of the arguments in a function call


Possible Duplicate:
order of evaluation of function parameters

Is it safe to use the following construction in C/C++?

f(g(), h());

where g() is expected to be evaluated first, then h().

Do all compilers show the same behavior on all architectures?


Solution

  • NO! There is no guarantee what order these are carried out in. Only that both g() and h() are carried out before f(). See this: http://www.gotw.ca/gotw/056.htm I think there's an updated C++11 version of that, I'll have a look.

    Edit: C++11 version http://herbsutter.com/gotw/_102/

    Edit 2: If you really want to know what specific compilers do, try this: http://www.agner.org/optimize/calling_conventions.pdf Section 7 (page 16) may be relevant, though it's a bit over my head, but for instance __cdecl calling convention means arguments are passed from right to left (at least stored that way), whereas for __fastcall "The first two DWORD or smaller arguments are passed in ECX and EDX registers; all other arguments are passed right to left." (http://msdn.microsoft.com/en-us/library/6xa169sk%28v=vs.71%29.aspx)

    So it does vary for different compilers.

    Much later edit: It turns out that for constructors using the initializer list syntax (curly braces {}), order of evaluation is guaranteed (even if it is a call to a constructor that does not take a std::initializer_list. See this question.