0

I made a class called Room and i need to generate an array with random size, but compiler says it needs a constant value. My code:

int randN(int from, int to) {
    return from + rand() % (to - from + 1);
}

void main() {
    srand(time(nullptr));
    
    int roomSize = randN(5, 13);
    const int rs = roomSize;
    Room raray[rs];

}

I tried to write:

const int roomSize(randN(5,13));

but it doesn't work.

  • 3
    Why not use `std::vector`? – Stephen Newell Feb 23 '23 at 17:53
  • 12
    variable size arrays (ie not known at compile time) are not standard c++ (some compilers support them as an extension). use std::vector – pm100 Feb 23 '23 at 17:53
  • 4
    And unrelated, but don't use `rand` (https://stackoverflow.com/questions/24566574/using-c11s-random-header-what-is-the-correct-way-to-get-an-integer-between). And `main` should return an `int`. – Stephen Newell Feb 23 '23 at 17:55
  • There are few scenarios where a `std::vector` is not suitable – if you still encounter one then best you can do is allocate the array at its possible maximum size (you might prefer `std::array` over classic raw arrays) and fill it up only partially while tracking the number of elements contained. Just don't operate on that right from the beginning, first choice should always be the `std::vector`. – Aconcagua Feb 23 '23 at 18:02
  • Just as a side note: `int const n = nonConstexprFunction();` doesn't yield a compile time constant, but an ordinary int that's immutable after assignment. – Aconcagua Feb 23 '23 at 18:05
  • the compiler is correct. you didnt ask a question – 463035818_is_not_an_ai Feb 23 '23 at 18:05
  • 1
    @StephenNewell -- `rand()` is just fine here; it's good enough, and it's much easier to use than the newer stuff. – Pete Becker Feb 23 '23 at 18:23

0 Answers0