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

坚强是说给别人听的谎言 提交于 2019-12-12 02:55:30

问题


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?


回答1:


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.




回答2:


See 1.9 Program execution:

Certain other aspects and operations of the abstract machine are described in this International Standard as unspecified (for example, order of evaluation of arguments to a function). Where possible, this International Standard defines a set of allowable behaviors.

and 8.3.6 Default arguments, 9:

[...] Default arguments are evaluated each time the function is called. The order of evaluation of function arguments is unspecified. Consequently, parameters of a function shall not be used in a default argument, even if they are not evaluated. [...]




回答3:


No, it's not safe - if you need a guaranteed order of evaluation, e.g. because of side effects, then you will need to do something like this:

foo = g();
bar = h();
f(foo, bar);



回答4:


No, the order of evaluation of arguments with respect to each other is unspecified. The only guarantee that you have is that they will not be executed concurrently with each other.




回答5:


No. The standard don't define the order of evaluation in that case, and each compiler may do whatever it wants. I think that most of them (and specially gcc) evaluate the rightest first.



来源:https://stackoverflow.com/questions/9116036/c-c-evaluation-of-the-arguments-in-a-function-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!