Question

Consider the following snippet:

#include <iostream>
using namespace std;

int a[10][2];
int b[10][2];

int main(){

  //intended
  cout << a[0][0] - b[0][0] << endl;

  //left out dimension by mistake
  cout << a[0] - b[0] << endl;

}

Obviously (or maybe not per comments) the second case is valid pointer arithmetic in both C and C++ but in the code base I am working with it is generally a semantic mistake; a dimension has usually been left out in a nested for loop. Is there any -W flag or static analysis tool that can detect this?

Was it helpful?

Solution

You could use std::array which will not allow that:

    using d1=std::array<int, 2>;
    using d2=std::array<d1, 10>;

    d2 a;
    d2 b;

    std::cout << a[0][0] - b[0][0] << endl;  // works as expected

    std::cout << a[0] - b[0] << endl;        // will not compile

OTHER TIPS

Another option is to use a specialized multidimensional array library with appropriate operator error handling, such as boost::multi_array (http://www.boost.org/doc/libs/1_55_0/libs/multi_array/doc/user.html). This is usually a better idea then using nested containers or POD arrays.

If this is only concern for << operator as in example, overload of operator << for int* might help - you can overload operator to generate compile-time error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top