5
#include <iostream> using namespace std; void f(int x, int y){ cout << "x is " << x << endl; cout << "y is " << y << endl; } int main(){ int i = 7; f(i--,i-- ); cout << i << endl<< endl; } 

We expected the program to print "x is 7 \n y is 6 \n i is 5"

but the program printed "x is 6 \n y is 7 \n i is 5"

2 Answers 2

11

f(i--,i-- ); invokes Undefined Behaviour. Don't write such code.

EDIT :

Comma , present in the above expression is not Comma operator. It is just a separator to separate the arguments(and which is not a sequence point.)

Furthermore the order of evaluation of arguments of a function is Unspecified but the expression invokes Undefined Behaviour because you are trying to modify i twice between two sequence points.

Uff I am tired. :(

Sign up to request clarification or add additional context in comments.

6 Comments

Fully agree. It is very bad to use {in,de}crement operators twice in the same statement.
@Downvoter : The answer is perfectly correct. Please explain your downvote.
@Svisstack : , present in the function call is not comma operator, it is just a separator and it is not a sequence point.
@Svisstack: Are you sure they are pushed onto a stack in reverse order on all platforms...?
@Swisstack: The argument evaluation order is unspecified, so it can be in the order in which they are pushed on the stack, or not. C/C++ doesn't promise you anything there. In this case additionally the value of i is modified twice in the same expression (without any sequence point in between). If you do that, the behavior is undefined. (See §5/4 "Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression.")
|
2

This tells you that the parameters are being evaluated from right-to-left, not left-to-right as expected. This may be because of the calling convention or otherwise, but it would generally be a bad idea to rely on the order of function parameter evaluation.

2 Comments

It's the calling convention, arguments are pushed from right-to-left onto the stack
@Aillyn: WRONG. They may be how it works for your compiler but it is not actually defined in the standard. Who says the parameters are even placed on the stack for a function call. (If this was C you may be more correct but this is C++ and the ABI is undefined (deliberately)).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.