Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect accidental elided dimension in C++

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?

like image 835
frankc Avatar asked Dec 23 '13 22:12

frankc


1 Answers

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
like image 99
Glenn Teitelbaum Avatar answered Sep 29 '22 04:09

Glenn Teitelbaum