1

Is it possible to initialize an integer array inline when calling a method in c++ (avr-g++)?

This is what I tried:

A({2, 4, 8, 3, 6});

void A(int* b) {

}

And I got this error:

cannot convert '' to 'int*' for argument '1' to 'void A(int*)' cannot convert '' to 'int*' for argument '1' to 'void A(int*)'

MuhsinFatih
  • 1,891
  • 2
  • 24
  • 31

2 Answers2

4

Looking at my old question I figured out I actually know the answer to this now. Here goes:

void A(int *b) {

}

void foo() {
    A((int[]){1,2,3});
}
MuhsinFatih
  • 1,891
  • 2
  • 24
  • 31
  • 1
    Compound literals are not legal constructs in C++. https://stackoverflow.com/questions/28116467/are-compound-literals-standard-c – bernie Apr 01 '20 at 09:13
  • **Be careful with this usage**: gcc/g++ (10.2) won't allow me to do this. I get "error: taking address of a temporary array". Apple clang (14.0) does allow it but if I compile with the `-pedantic` switch, I get "warning: compound literals are a C99-specific feature [-Wc99-extensions]". – Ryan H. Nov 02 '22 at 09:25
3

Not with a raw pointer. But you could do that with a std::vector in C++11:

void A(std::vector<int> b) {

}

A({2, 4, 8, 3, 6}); // b.size() == 5

Or just a function template that deduces the array size:

template <size_t N>
void A(const int (&b)[N]) {
}
Barry
  • 286,269
  • 29
  • 621
  • 977
  • Sorry for unaccepting your answer. To compensate I upvoted (actually this is a valid answer so I would upvote regardless. Didn't have the reputation to upvote before). Later I learned about compound literals, posted as answer as it seemed more appropriate – MuhsinFatih Jun 10 '17 at 19:24