Objective-C function with default parameters?

Objective CFunctionParametersDefault Value

Objective C Problem Overview


> Possible Duplicates:
> Optional arguments in Objective-C 2.0?
> Objective-C Default Argument Value

I'm writing a C function in Objective-C. I want a default value for my last parameter.

I've tried:

foo(int a, int b, int c = 0);

but that's C++.

I've also tried:

foo(int a, int b, int c)
{
    ...
}

foo(int a, int b)
{
   foo(a, b, 0);
}

But that's also C++.

Is there a way to do this in Objective-C instead?

Objective C Solutions


Solution 1 - Objective C

There's no default parameters in ObjC.

You can create 2 methods though:

-(void)fooWithA:(int)a b:(int)b c:(int)c {
  ...
}
-(void)fooWithA:(int)a b:(int)b {
  [self fooWithA:a b:b c:0];
}

For C : there's nothing special added to the C subset by using ObjC. Anything that cannot be done in pure C can't be done by compiling in ObjC either. That means, you can't have default parameters, nor overload a function. Create 2 functions instead.

Solution 2 - Objective C

No, objective-c does not support default parameters. See similar question

Solution 3 - Objective C

You can write a C function with a variable length argument list. You can use '...' as the data type for one of your function's declared parameters to specify where in the parameter list the variable argument list begins. (That allows you to have one or more required arguments before the start of the list.)

printf() is an example of a function that is written using this facility (known as varargs).

printf(const char *restrict format, ...);

Here, the first argument is required, and then can be followed by zero or more additional arguments.

If you wrote your function this way, it could supply a default value for the missing parameter.

Solution 4 - Objective C

For a C function - no. For an Objective C class method - yes, you just do two methods, one of them one parameter short, calling the other method.

Or you can rename your sources to .mm and C functions magically become C++.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBrian PostowView Question on Stackoverflow
Solution 1 - Objective CkennytmView Answer on Stackoverflow
Solution 2 - Objective CVladimirView Answer on Stackoverflow
Solution 3 - Objective CjlehrView Answer on Stackoverflow
Solution 4 - Objective CSeva AlekseyevView Answer on Stackoverflow