How to pass an array of a function without an instance of a variable, in C ++

Can I do this in C ++ (if so, what is the syntax?):

void func(string* strs) { // do something } func({"abc", "cde"}); 

I want to pass an array to work without creating it as a variable. Thanks for the suggestions.

+6
c ++
source share
4 answers

This cannot be done in current C ++, as defined by C ++ 03.

The function you are looking for is called compound literals. It is present in C, as defined by C99 (with certain features of C, of ​​course), but not in C ++.

A similar function is also planned for C ++, but it is not there yet.

+9
source share

I don't think you can do this in C ++ 98, but you can with initializer_lists in C ++ 1x.

0
source share

As written, you cannot do this. The function expects a pointer to a string. Even if you manage to pass the array as a literal, the function call will generate errors because the literals are considered constant (thus, the array of literals will be of type const string* , not string* , as the function expects).

0
source share

Use a variable function to pass unlimited unwritten information to a function. Then do whatever you want with the data passed in, for example, pasting them into an internal array.

variational function

0
source share

All Articles