0

I was digging through some of Android source code files and found this array declared inside a function:

float a[n][m];

The context:

static bool solveLeastSquares(const float* x, const float* y,
        const float* w, uint32_t m, uint32_t n, float* outB, float* outDet) {

    float a[n][m]; // <-------- this array
    for (uint32_t h = 0; h < m; h++) {
        a[0][h] = w[h];
        for (uint32_t i = 1; i < n; i++) {
            a[i][h] = a[i - 1][h] * x[h];
        }
    }

    // continues...

The code can be found here (line 465): https://android.googlesource.com/platform/frameworks/native/+/refs/heads/master/libs/input/VelocityTracker.cpp

I tried to compile in Visual Studio, but, as I expected, it failed because m and n cannot be used as constant values.

Since this is from Google Git and is part of Android's native framework, we know it (probably) works, but can anyone explain how this is possible?

  • 2
    Because some compilers enable non-standard code either by default or with flags. – crashmstr Mar 31 '20 at 22:03
  • 4
    does this answer your question? https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard – 463035818_is_not_an_ai Mar 31 '20 at 22:09
  • It does, thanks. From the answers in that question, I can see that this is a controversial feature. This function is part of a process to calculate the scrolling velocity of ScrollViews on Android, so I imagine performance is a concern (I am still a student, so I can't weight the pros and cons of having non-standard code like this). – Rodolfo Ribeiro Mar 31 '20 at 22:36

1 Answers1

1

Standard c++ does not support variable-length arrays, several compilers - notably gcc and clang - do however support them as a carry-over from C (which has supported VLAs since c99). However, Microsoft Visual C++ is not one of those compilers.

SoronelHaetir
  • 14,104
  • 1
  • 12
  • 23
  • Interesting. I didn't know about such feature, and it made me curious about how the compiler handles it. I will look into it, thanks. – Rodolfo Ribeiro Mar 31 '20 at 22:37