karthiksatyanarayana
karthiksatyanarayana

Reputation: 109

How to optionally pass variable arguments in C

Consider below function:

void foo(int n,...);

I need to call this function, "optionally" passing variable arguments.

Is it possible?

Something like this:

foo(10, (bIsJobDone ? "OK" : xxx) );

I am not able to figure out what to put in place of xxx (xxx should convert to nothing) and also how to avoid "," after 10, if I don't have to pass any variable arg to foo?

Note: i can't change signature of "foo".

Upvotes: 0

Views: 141

Answers (3)

mksteve
mksteve

Reputation: 13073

If a function has been written for variable number of arguments (e.g. printf), then it is possible to pass a variable number of arguments to a function.

These work with either of two patterns

The Map Pattern

Like printf, an early non optional parameter describes the remaining parameters which have been added. These are then plucked from the stack appropriately.

The terminating pattern

A function can be written to sum a set of parameters, which have some mechanism for detecting the terminator.

int sum( int first_arg, ... );

Where a special token is added to the function to call correctly.

If a function has been written to only accept a fixed number of arguments, you have to pass that number of arguments.

This is because the calling code, and the called code have to agree on how much stack is used. Any difference in this contract, will result in undefined behavior, which can mean a crash, or you program may be exploitable by a malicious actor.

Given that the function has a set number of parameters, you need to supply all of these.

Upvotes: 0

Yunnosch
Yunnosch

Reputation: 26703

As long as you got the called function correctly prototyped and defined (not easy...),
calling it with one or two parameter, depending on a condition is easy:

if(bIsJobDone)
{    foo(10, "OK");
} else
{    foo(10);
}

The alternative, to squeeze it into a ternary operator, is possible, but considered unreadable by many (just a matter of opinion of course) and not needed for the void-returning prototype you have shown in your question.

Upvotes: 2

CinCout
CinCout

Reputation: 9619

Call it separately:

bIsJobDone ? foo(10, "OK") : foo(10);

Upvotes: 0

Related Questions