Post and pre increment, decrement in 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 \ ny is 6 \ n i is 5"

but the program printed "x equals 6 \ ny equals 7 \ n i equals 5"

+6
c ++
source share
2 answers

f(i--,i-- ); causes Undefined Behavior . Do not write such code.

EDIT :

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

Also, the evaluation order of the arguments to the Unspecified function, but the expression calls Undefined Behavior, because you are trying to change i twice between two points in the sequence.

Uff I'm tired. :(

+11
source share

This suggests that the parameters are evaluated from right to left, and not from left to right, as expected. This may be caused by a calling convention or otherwise, but it would usually be a bad idea to rely on the order in which the parameters of the function are evaluated.

+2
source share

All Articles