Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the order of destruction of function arguments?

If some function f with parameters p_1, ..., p_n of types T_1, ..., T_n respectively is called with arguments a_1, ..., a_n and its body throws an exception, finishes or returns, in what order are the arguments destroyed and why? Please provide a reference to the standard, if possible.

EDIT: I actually wanted to ask about function "parameters", but as T.C. and Columbo managed to clear my confusion, I'm leaving this question be about the arguments and asked a new separate question about the parameters. See the comments on this question for the distinction.

like image 715
jotik Avatar asked May 02 '16 21:05

jotik


People also ask

Does order of arguments matter for a function?

Yes, it matters. The arguments must be given in the order the function expects them.

What is the first argument of a function?

The first argument in the function is assigned to the first parameter in the handler definition, and so on. In this example, if the caller specifies only two arguments, the second argument will be used as the second parameter ( chan ).

What are the parts of the functions arguments?

All R functions have three parts: the body() , the code inside the function. the formals() , the list of arguments which controls how you can call the function. the environment() , the “map” of the location of the function's variables.

When calling a function the arguments should be in order?

3. Positional Arguments. During a function call, values passed through arguments should be in the order of parameters in the function definition. This is called positional arguments.


1 Answers

I did not manage to find the answer in the standard, but I was able to test this on 3 most popular C++ compliant compilers. The answer of R Sahu pretty much explains that it is implementation defined.

§5.2.2/8: The evaluations of the postfix expression and of the arguments are all unsequenced relative to one another. All side effects of argument evaluations are sequenced before the function is entered.

Visual Studio C++ Compiler (Windows) and gcc (Debian)
Arguments are constructed in order reverse to their declaration and destroyed in reversed order (thus destroyed in order of delcaration):

2
1
-1
-2

Clang (FreeBSD)
Arguments are constructed in order of their declaration and destroyed in reversed order:

1
2
-2
-1

All compilers were instructed to treat the source code as C++11 and I used the following snippet to demonstrate the situation:

struct A {     A(int) { std::cout << "1" << std::endl; }     ~A() { std::cout << "-1" << std::endl; } };  struct B {     B(double) { std::cout << "2" << std::endl; }     ~B() { std::cout << "-2" << std::endl; } };  void f(A, B) { }  int main() {     f(4, 5.); } 
like image 179
Zereges Avatar answered Oct 12 '22 04:10

Zereges