0

I want to create an array inside a function just like this:

int function(int a){
    int something[a]{};
    return something;
}

but the next error "expression must have a constant value" appear.

  • `int something[a]{};` What did you intend this line to do? Simply create an `array` of size `a`? – GBlodgett Sep 09 '18 at 02:28
  • C++ does not support VLA, use `std::vector` instead – Slava Sep 09 '18 at 02:37
  • Arrays must have a constant size. "a" is not a constant. Open your C++ book to the chapter that explains how to use a `std::vector`, and read it. – Sam Varshavchik Sep 09 '18 at 02:38
  • Do you need this? `int* function(int a){ int* something = new int[a]; return something; }` – PraAnj Sep 09 '18 at 04:26
  • Forget about all of this and use `std::vector`. However, what you really want to do here remains a bit of a mystery, because your `return` statement makes no sense. – Christian Hackl Sep 09 '18 at 06:35
  • Stuff like `int something[a]{};` isn't valid C++, because [C++ doesn't have variable length arrays](https://stackoverflow.com/q/1887097/9254539). You should use an `std::vector` instead. – eesiraed Sep 09 '18 at 23:58

1 Answers1

-1

Your code doesn't really make sense, you are trying to create an array something, and then return an array from a function that is supposed to return an int. Guessing at your intentions,

If you want to return an int from an array based on index a, you could:

test.cpp

#include <iostream>

int function(int a){
    int something[] = {1,2,3};
    return something[a];
}

int main()
{
    std::cout << function(1) << std::endl;
}

Compile using $ g++ test.cpp -o test Run using $ ./test

JBaczuk
  • 13,886
  • 10
  • 58
  • 86