yegor256
yegor256

Reputation: 105043

How to pass array to function without variable instantiation, in C++

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

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

I want to pass an array to a function, without instantiating it as a variable.

Upvotes: 13

Views: 2797

Answers (4)

AnT stands with Russia
AnT stands with Russia

Reputation: 320361

It can't be done in the current C++, as defined by C++03.

The feature you are looking for is called "compound literals". It is present in C language, as defined by C99 (with C-specific capabilities, of course), but not in C++.

A similar feature is planned for C++ as well, but it is not there yet.

Upvotes: 13

bta
bta

Reputation: 45057

As written, you can't do this. The function expects a pointer-to-string. Even if you were able to pass an array as a literal, the function call would generate errors because literals are considered constant (thus, the array of literals would be of type const string*, not string* as the function expects).

Upvotes: 0

Gregor Brandt
Gregor Brandt

Reputation: 7799

Use a variadic function to pass in unlimited untyped information into a function. Then do whatever you want with the passed in data, such as stuffing it into an internal array.

variadic function

Upvotes: 0

Firas Assaad
Firas Assaad

Reputation: 25750

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

Upvotes: 0

Related Questions