-1

The following code

void function(char* p1, char* p2)
{
    // [...]
    return;
}
char* print(char* msg)
{
    printf("%s\n", msg);
    return msg;
}
function(print("first"), print("second"));

gives output like this: second first

I'm curious why its executing functions from right to left.

Rocik
  • 9
  • 3
  • 2
    The standard does not specify the order of parameter evaluation, it is up to the vendor to implement this – EdChum Apr 16 '14 at 11:00
  • 2
    See related: http://stackoverflow.com/questions/2934904/order-of-evaluation-in-c-function-parameters – EdChum Apr 16 '14 at 11:02

2 Answers2

1

The C++ standard, Function call (5.2.2/4), says:

When a function is called, each parameter shall be initialized with its corresponding argument. [ Note: Such initializations are indeterminately sequenced with respect to each other — end note ]

Your compiler, for that piece of code chose to initialize the parameters in right to left order. Presented with different code, or even the same code, your compiler could make a different choice. The order is simply unspecified by the standard and you cannot rely on it.

If you wish to enforce a particular order you must sequence these function calls explicitly.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
-1

This Problem is because of Stack Memory used by the function.

function(print("first"), print("second"));

the execution of this function will be as follows:

// Push Operation
1. Call function()
2. Call print("First")
3. Call Print("Second")

// Pop Operation

4. Execute Print("Second")
5. Execute Print("First")
6. Execute function()

Because of this the output is Second First.

For More Information You Can Refer Link.

Hope this will Help you to Understand

Community
  • 1
  • 1
A B
  • 1,461
  • 2
  • 19
  • 54