Ali
Ali

Reputation: 19672

c function declaration in xcode / to replace NSLog with something that behaves differently in debug and release

It is a rather silly question! but in the following function how do you use the remaining arguments passed in:

void NSLog(NSString *format, ...)
{
    //here I can use "format" but how can I use the remaining arguments?
}

It is hard to find the answer to this question because I cant search for "..." ?! By the way that is how NSLog works but I put it here just as an example my question has nothing to do with NSLog.

Upvotes: 4

Views: 2231

Answers (4)

pohsyb
pohsyb

Reputation: 206

Use a variable argument list:

void NSLog(NSString *format, ...)
{
    va_list ap;
    va_start(ap, format);

    while( (value = va_arg(args, NSString *) ){
        // Do something with value. This is assuming they are all strings
    }

    // or pass entire list to another function
    NSLog_VA( format, ap );

    va_end(ap);
}

void NSLog_VA( NSString * format, va_list args )
{
    // do something with va_list here
}

Edit: Since you want a debug only log:

#ifdef DEBUG 
#define DebugOnly_Log(format, args...) NSLog(format, ##args) 
#else 
#define DebugOnly_Log(format, args...) // defined to nothing
#endif 

Upvotes: 5

Ali
Ali

Reputation: 19672

OK, thanks all, I followed the direction you gave me and this is the solution: As I understand it, there is no general/portable solution to the problem of receiving variable number of arguments and passing them to another function that accepts variable number of arguments (as mentioned her http://c-faq.com/varargs/handoff.html ).

But I wanted to implement an NSLog alternative (I call it AliLog ) which during debugging just behaves like NSLog but for the release version does nothing (or does something other than writing to consol).

here is my solution:

void AliLog(NSString *format, ...) 
{
#ifdef DEBUG
    va_list args;
    va_start(args, format);
    NSLogv(format, args);
    va_end(args);
#else
    // do nothing! or something that makes sense in a release version
#endif
}

The magic is in NSLogv here.

Upvotes: 0

Nick Van Brunt
Nick Van Brunt

Reputation: 15464

Have a look at stdarg.h

It might look a bit like -

void NSLog(NSString *format, ...)
{

  va_list args;
  va_start(args,format);
  vprintf([format cString], args);
  va_end(args);
}

Upvotes: 4

Sherm Pendley
Sherm Pendley

Reputation: 13612

That's called a variadic function, and you can access its arguments by using the macros in stdarg.h.

Upvotes: 3

Related Questions