Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Pass array created in the function call line

Tags:

c++

arrays

How can I achieve a result like somebody would expect it according to the following code example:

// assuming: void myFunction( int* arr );

myFunction( [ 123, 456, 789 ] );

// as syntactical sugar for...

int values[] = { 123, 456, 789 };
myFunction( values );

The syntax I thought would work spit out a compile error.

  • How can I define an argument array directly in the line where the function is called?
like image 750
Jarx Avatar asked Feb 15 '11 22:02

Jarx


1 Answers

If you were using C (C99, specifically), you could have used a compound literal here:

myFunction( (int []) {123, 456, 789} );

But the are not part of C++ (your compiler may still support them, though). In C++0x, you could use an initializer list, but they don't decay to pointers (not that using raw pointers is a good idea to begin with).

Although if you change the signature of myFunction to void myFunction( const int* arr ), you would be able to do the contrived call

myFunction( std::initializer_list<int>({123, 456, 789}).begin() );
like image 139
Cubbi Avatar answered Oct 26 '22 22:10

Cubbi