0

#include <iostream>
using namespace std;
int main()
{
    int i, x, j, t;
    int size = rand() % 100;//random number
    int a[size];// random number is the size of array
    
    //array filling
    
    for (i = 0; i <= size; i++) {
        a[i] = rand() % 100;//new random number -> gets assigned as part of the array
    }
    for (x = 0; x < size; x++) {
        for (j = x + 1; j < size; j++)
        {
            if (a[j] < a[x]) { //if x > x+1 sortieren
                t = a[x];
                a[x] = a[j];
                a[j] = t;
            }
        }
    }
    for (x = 0; x < size; x++) {
        cout << a[x] << "\t";
    }
    return 0;
}

Array declaration not working for me but its working for my colleague. It seems that the IDE insists that the array has to be a constant.

  • 4
    Your colleague is relying on a compiler extension known as "Variable Length Array" typically enabled by default on GCC. `int a[size];` is not allowed in C++ unless `size` is a constant expression (evaluated at compile time). – François Andrieux Nov 05 '21 at 21:49
  • 4
    `a[i]` will access `a` out of bounds when `i == size`. The condition in the loop should be `i < size` instead of `i <= size`. – François Andrieux Nov 05 '21 at 21:50
  • 1
    Sometimes flawed / broken programs execute and give you expected values. This is the worst behavior of undefined behavior. The bug @FrançoisAndrieux pointed out could be the reason why this code fails if you have a compiler that supports VLAs – drescherjm Nov 05 '21 at 21:51
  • 1
    `int a[size]` -> `std::vector a(size)`. Then your code is portable and will work with any C++ compiler. Then you can use `std::sort(a.begin(), a.end())` in place of your bubble sort. Happy days! – Bathsheba Nov 05 '21 at 21:59

1 Answers1

3

Variable length arrays are not valid as per the C++ standard. There are some compilers that accept it as a non-standard extension. I'd advise to avoid VLAs and instead use a std::vector when you need a dynamic array.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70