tags:

views:

131

answers:

2
#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"

+11  A: 

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. :(

Prasoon Saurav
Fully agree. It is very bad to use {in,de}crement operators twice in the same statement.
Benoit
@Downvoter : The answer is perfectly correct. Please explain your downvote.
Prasoon Saurav
@Svisstack : `,` present in the function call is not `comma operator`, it is just a separator and it is not a sequence point.
Prasoon Saurav
@Svisstack: Are you sure they are pushed onto a stack in reverse order on all platforms...?
Matti Virkkunen
@Prasoon Saurav: i know
Svisstack
@Svisstack: I hear some calling conventions use registers to pass argument values. How does that fit in with everything?
Matti Virkkunen
@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.")
sth
+2  A: 

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.

Alexander Rafferty
It's the calling convention, arguments are pushed from right-to-left onto the stack
Aillyn
@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)).
Martin York