0

I keep receiving an error saying "Expression must have a constant value the value of variable 'n1' cannot be used as a constant ". I don't know what am I use suppose to do to fix it.

void merge(DataType theArray[], int first, int mid, int last)

int i, j, k;
int n1 = mid - first + 1;   
int n2 = last - mid;

 int L1[n1], R1[n2];  //n1, n2 are giving me the same problem mentioned above

for (i = 0; i < n1; i++)
    L1[i] = theArray[first + i];
for (j = 0; j < n2; j++)
    R1[j] = theArray[mid + 1 + j];
shazghe
  • 1
  • 1
  • 1
    You don't show an opening brace `{` for your function snippet. – Passerby Oct 26 '21 at 00:38
  • 1
    Nothing in the given code suggests that `n1` is a constant value. For an array size, the variable must be a compile-time constant so that the compiler knows how much memory is required and how to set up any indexing math required. Some compilers allow [variable length arrays](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard) as an extension, but your compiler is clearly not one of these. Consider using [`std::vector`](https://en.cppreference.com/w/cpp/container/vector) instead. – user4581301 Oct 26 '21 at 00:43
  • Also considering changing whatever materials you are learning from to books and lesson plans that cover Standard C++ to avoid problems like this in the future. – user4581301 Oct 26 '21 at 00:44
  • Which compiler version you are using? To the best of my knowledge it should be OK when compile the code with C++14 and C++17. – TaQuangTu Oct 26 '21 at 00:49
  • `int L1[n1]`, where `n1` is some variable, is not valid C++. See the duplicate question for more information, C++ simply does not work this way. – Sam Varshavchik Oct 26 '21 at 00:55
  • 3
    @TaQuangTu No version of the C++ Standard allows Variable Length Arrays, and it is unlikely that they will be added in the future. – user4581301 Oct 26 '21 at 01:08

0 Answers0