C++ expression evaluation order

c++, evaluation

Solution

In my opinion, this boils down to order of evaluation.

The standard says -

(5.4) Except where noted, the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified.

Which fits the bill exactly. The values of i and j may be evaluated before the call to by_index(), or after it. You can't tell - this is unspecified.

I will add that the form that solves your problem is far more readable in my eyes, and I would have used it regardless of correctness of the first form...

Problem

i ran into a curious problem regarding evaluation of expressions: ``` reference operator()(size_type i, size_type j) { return by_index(i, j, index)(i, j); // return matrix index reference with changed i, j } matrix& by_index(size_type &i, size_type &j, index_vector &index) { size_type a = position(i, index); // find position of i using std::upper_bound size_type b = position(j, index); i -= index[a]; j -= index[b]; return matrix_(a,b); // returns matrix reference stored in 2-D array } ``` I have thought matrix(i,j) will be evaluated after the call to buy_index, so that i, j will be updated. this appears to be correct, i verified in debugger. however, for some types of matrix, specifically those which have to cast size_type the something else, for example int, the update in by_index is lost. modifying code slightly removes the problem: ``` reference operator()(size_type i, size_type j) { matrix &m = by_index(i, j, index); return m(i, j); } ``` do you know why the first operator misbehaves? thanks prototypes which work and which do not ``` inline reference operator () (size_t i, size_t j); // ublas, size_type is std::size_t reference operator () (int i, int j); // other prototype, size_type is int ``` in debugger backtrace stack looks like this: - i = 1 upon entry to operator() //okay - i = 0 after finish from by_index //okay - i = 1 upon entry to matrix:: operator() //not right, should be 0

Original source

Related problems