1

I have just finished my code, I am stuck on these last two errors: "the value of parameter "n" cannot be used as a constant." I am using "int n" in my function to calculate average time.

void findavgTime(int option, int pids[], int arrivals[], int n, int bursts[], int quanta) { 

int resp[n], ta_time[n], avg_resp_time = 0, avg_ta_time = 0; 

How should I go by this?

Mr.C64
  • 41,637
  • 14
  • 86
  • 162
GMoney
  • 11
  • 2

2 Answers2

3

In C++, the size of an array must be a compile time constant. So you cannot write code like:

int n = 10;
int arr[n];    //incorrect

Correct way to write this would be:

const int n = 10;
int arr[n];    //correct

For the same reason the following code is incorrect in your code as well:

int resp[n], ta_time[n];//incorrect because n must be a compile time constant

You can use std::vector<> for your purpose instead of using built in arrays. So instead of creating arrays you can have/create std::vector named resp and ta_time as follows:

//n denotes the size. You can also use std::vector::reserve for requesting that the vector capacity be at least enough to contain n elements
std::vector<int> resp(n); 
std::vector<int> ta_time(n);
Jason
  • 36,170
  • 5
  • 26
  • 60
  • nitpick: in modern C++, we'd use `constexpr` instead of `const` for compile-time constants. –  Oct 25 '21 at 17:35
  • Note that `const` have two meanings depending on context: In the context shown here it's a compile-time constant and can be used for arrays sizes. But if it's a class-member or a function argument then it only means "read only" and it not a compile-time constant and can't be used for e.g. array sizes. – Some programmer dude Oct 25 '21 at 17:37
  • @Someprogrammerdude Yup i am aware of that. – Jason Oct 25 '21 at 17:39
  • more nitpick: `//incorrect because n must be known at compile time` The compiler does know the value also in `int n = 10; int arr[n];` but it isnt a constant expression – 463035818_is_not_an_ai Oct 25 '21 at 18:15
  • @463035818_is_not_a_number yeah i changed it to `//incorrect because n must be a compile time constant` . – Jason Oct 26 '21 at 03:05
1

Consider replacing your variable-length arrays:

int resp[n], ta_time[n]

with modern C++ std::vector instances:

#include <vector> // for std::vector

std::vector<int> resp(n);
std::vector<int> ta_time(n);

You can still access vector elements using the usual v[i] syntax with a 0-based index, e.g.:

resp[2] = 100; // Access the 3rd element in the vector

VLAs (variable-length arrays) are not part of the C++ standard. You can only create arrays with compile-time known size, e.g.

constexpr int n = 100; // compile-time constant
int resp[n];
Mr.C64
  • 41,637
  • 14
  • 86
  • 162