0

I searched for my problem but I couldn't find one.

I'm working with VS Code (version 1.55) in C++. I'm trying to declare 2 arrays inside a function using one of its parameters to define the width. I need this because I have to initialize them, inside the same function, in a different way given their width, like this:

double MyFunc(/*other parameters*/ int points){
  
  double arr1[points];
  double arr2[points];

  if(points == 2){
    // initialization
  }
  else if(points == 3){
    // initialization
  }
  else if(points == 4){
    // initialization
  }
// Operations with the arrays etc
return 1.7;  // Arbitrary value just to make this code working
}

If I save the file like this, VS Code tells me that there's a problem, which is: "expression must have a constant value -- the value of parameter "points" cannot be used as a constant". But I can compile and execute it anyway (I tried with cygwin and it's all ok). Is there a way to get rid of this "false" problem?

  • 4
    Use a `std::vector` instead. – ChrisMM Apr 29 '21 at 14:37
  • 4
    ***Is there a way to get rid of this "false" problem?*** This is not a false problem. This is a real problem. VLAs are a feature that are not part of standard c++. Some compilers who support the `c` language implement this as an extension to `c++` however the `c++` standard does not have VLAs. – drescherjm Apr 29 '21 at 14:39
  • To answer the question asked... change the language version in the C++ plugin from e.g. "c++14" to "gnu++14" so it knows you aren't caring to write C++ code. But then you should use the [tag:g++] tag not [tag:c++] because the language you are writing in is not C++ but the gnu variation. – Ben Voigt Apr 29 '21 at 16:06
  • @ChrisMM As musch as I want to use all my c++ knowledge, including vector and other libraries, my professor forced me to follow step by step. It's for my university course on "numerical Algorithms", so I can't exactly do as I want unfortunately :( – Desfortune Apr 30 '21 at 15:14
  • @drescherjm Thank you, so basically it's the other compiler (cygwin) that implement this. I should say that to my professor, he's convinced the other way lol – Desfortune Apr 30 '21 at 15:17
  • @BenVoigt That's interesting... I'm sticking with c++ though, glad that I found it's a real problem and my prof is doing the other way :) – Desfortune Apr 30 '21 at 15:18
  • cygwin is using `gcc` which defaults to allow this VLA as an extension. – drescherjm Apr 30 '21 at 15:20
  • @EnricoSansone, you should inform your professor that that is **not** standard C++, and should definitely NOT be taught. – ChrisMM Apr 30 '21 at 15:47

0 Answers0