0

I have a situation where in I want one of the parameters of function to be optional. I wanted to know how I can achieve it..?

    int mapgw_cm_trace(int trapLog, char *pcMsgId, ...)

I want traplog parameter to be optional.

Or the otherway of looking at this is that, I set this parameter to a default value(say 1) if this parameter is not sent in the function call...else use the vaLue sent in the function call. Is it possible to achieve this..? I do not want to use va_args ()

6
  • 1
    do not want to use va_args - then why do you have ... in your function's declaration? Or it just shows, that there are other irrelevant parameters (but fixed number)? Commented Apr 16, 2013 at 6:36
  • 1
    Don't think there is default value for parameter or something like optional parameter in C. Commented Apr 16, 2013 at 6:36
  • 3
    How would you call a function that has its first parameter optional? Commented Apr 16, 2013 at 6:43
  • I'm using ellipsis.. because I'm unaware of the no. of parameters, and its type as well.. I use these parameters just for logging.. and no parsing is done on these.. Commented Apr 16, 2013 at 8:34
  • @BartFriederichs : It is not about the parameter being first.. I can have the parameter in the middle as well.. Commented Apr 16, 2013 at 8:35

2 Answers 2

5

VA lists are bad for many reasons, most notably they have poor type safety. Avoid them.

The usual way to do that in C is to document the function, saying that if trapLog has value this or that, then it will not be used. If it should be possible for it have any value, then you can rewrite the function as:

int mapgw_cm_trace (const int* trapLog, char *pcMsgId)

and document that if trapLog == NULL it will not be used.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer. Can u elaborate a little more.. I don't think I understood...
0

Apart from the language features for optional parameters (that won't work here because they expect you to put those parameters last), there is always the possibility to write another function.

int mapgw_cm_trace(int trapLog, char *pcMsgId)

int mapgw_cm_trace_with_default_traplog(char *pcMsgId)
{
    // put your default as first parameter
    return mapgw_cm_trace(0, pcMsgId)
}

2 Comments

This is not possible in C, it does not support function overloading. The functions must have different names.
You are right, I edited it. Been using a C++ compiler for C for too long.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.