warning "operation on <variable> may be undefined"

g++, warnings

Solution

In `elems_[ptr] = data[ptr++]`, it is undefined whether `elems_[ptr]` is evaluated first or `data[ptr++]` is evaluated first. This is so, because `=` does not introduce a sequence point.

Depending on the order, `elems_[ptr] = data[ptr++]` yields different results. Hence the warning.

Problem

When I use overloading [][] operators in c++ to create a minimal matrix class ``` class matrix { private: vector<T> elems_; size_t nrows_; size_t ncols_; public: T const* operator[] ( size_t const r ) const { return &elems_[r * ncols_]; } T* operator[] ( size_t const r ) { return &elems_[r * ncols_]; } matrix (); matrix ( size_t const nr, size_t const nc ) : elems_( nr * nc ), nrows_( nr ), ncols_( nc ) { } matrix ( size_t const nr, size_t const nc, T const *data) : elems_( nr * nc ), nrows_( nr ), ncols_( nc ) { size_t ptr=0; for (int i=0;i<nr;i++) for (int j=0;j<nc;j++) elems_[ptr] = data[ptr++]; } } ``` g++ returns the warning `operation on ‘ptr’ may be undefined [-Wsequence-point]`. In previous post Why I got "operation may be undefined" in Statement Expression in C++? it is explained that `the last thing in the compound statement should be an expression followed by a semicolon` but not which purpose it serves. Does it mean that `g++` will always throw this warning for compound statements that have a for-loop at the end? If so can anyone explain why this is useful? I cannot think of any reason why anyone should be advised against ending a compound statement with a `for` loop.

Original source

Related problems