Question

In Objective-C you can say something like:

NSArray *anArray = [NSArray arrayWithObjects:obj,obj2, nil];

In case you are not familiar with objective-c it is saying I want an object of type of NSArray, anArray, and I want to call the method arrayWithObjects and then it acts as a sentinel and accepts as many parameters (which in this case are objects) until it reaches nil.

Is there any way to achieve something like this:

createObjects(o1,o2,o3,o4,-1);

Where the method of function can accept as many parameters until it reaches some key value?

Now, I am aware you can do sentinel stuff in C and C++, but is there a way to provide something like this to a method like they do in Objective-C?

Was it helpful?

Solution

You can write a variadic function and use a sentinel to locate the last real argument.

However, in C++, this is usually a bad idea because variadic functions are not type safe. It's preferred in C++ to put the elements you want to pass into a container, array, or class object of some kind and then pass that to the function. It's much less error-prone and much easier to verify.

OTHER TIPS

I think what you are looking for is varargs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top