views:

320

answers:

5

I'm trying to build a function that accepts an array in the following manner:

int inCommon = findCommon({54,56,2,10}, 4);

int findCommon(int nums[], int len){
  for(int i=0; i<len; i++)  cout<<nums[i]<<endl;
  return 1;
}

Note, that's not actually what my function does, but I do loop through the array. I'm just trying to determine if it's possible to pass an array like {54,56,2,10} instead of having to create an array and pass it? (like this:

int theArray[]= {54,56,2,10};
int inCommon = findCommon(theArray,4);
+2  A: 

No, I believe {} may only be used to initialize an array.

nan
Ah, figured as much, just wanted to see if it's possible.
Perchik
+2  A: 

You need C++0x!

http://en.wikipedia.org/wiki/C%2B%2B0x#Initializer_lists

Daniel Earwicker
+1  A: 

no. It is impossible. But you can create something like template T* arrayCreator(...) function which will create your array,
Or array wrapper with constructor with unspecified arguments count.
Or create object which will have overloaded operator coma or << and will create your array, findCommon( arrCreator() << 1 << 2 << 3 << 5, other parammeters ) - this method more type safe
Or waiting C++0x implementation.

bb
+5  A: 

This is not possible at the time. However, in the next C++ standard C++0x, this will be done using initalizer lists:

int findCommon(std::initializer_list<int> nums)
{
    std::initializer_list<int>::iterator it;
    for (it = nums.begin() ; it != nums.end() ; ++it)
    {
        std::cout << *it << std::endl;  
    }
    return 1;
}

See this presentation from Bjarne Stroustrup, and this article from Wikipedia

If you want to try C++0x features, you can check the last versions of gcc, that supports some of them.

Luc Touraille
GCC 4.4 supports initializer lists, getting the darwin port of it right now. Thanks!
Perchik
nice PDF. it also contains a link to the google video ( http://video.google.de/videoplay?docid=5262479012306588324 ) of bjarne about this.
Johannes Schaub - litb
+2  A: 

You can do what you want to do using variable argument lists.

EvilTeach