Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

post and pre increment, decrement in c++

Tags:

c++

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

like image 976
shikha garg Avatar asked Sep 25 '10 11:09

shikha garg


2 Answers

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

like image 141
Prasoon Saurav Avatar answered Sep 28 '22 03:09

Prasoon Saurav


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.

like image 41
Alexander Rafferty Avatar answered Sep 28 '22 03:09

Alexander Rafferty