kkh
kkh

Reputation: 4869

printf in macro in C

I have a macro as such

#define PTF(A,y)    fprintf(file,"%s",A,y);printf("%s %d",A,y);

so that it will print to file and console so for example i call this macro function

int y=9;
PTF("\nRound %d \n",y);

in a way I need the y=9 to be shown as part of the argument A so my fprintf in file will look like below

Round 9

because I have a lot of changes to make if I were to change this, hence hoping for an easy way out =)

Upvotes: 1

Views: 15318

Answers (5)

Remo.D
Remo.D

Reputation: 16512

The common idiom is to use do { ... } while (0) (some compilers will generate a warning for this) or the comma operator , and enclose your statements in parenthesis (but you can't use and control flow statement).

If you can rely on having a modern compiler (e.g. GCC 3+), you may use variadic macros to define a macro so that is similar to a regular printf.

I would go for something like:

#define PTF(...) (fprintf(file,__VA_ARGS__),printf(__VA_ARGS__))

so that PTF("Round %d",y) will print Round 9 (assuming y=9) both on file and on stdout.

The usual caveat on side-effects in macros apply: never, never use PTF("%d",y++).

Upvotes: 0

Dave
Dave

Reputation: 11162

Macros are the wrong way to do this; especially in this construction, you'll run into about every macro pitfall there is. Imagine:

if(condition)
    PTF("%s", foo);

Simply write a variadic function:

void
ptf(char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    vprintf(fmt, ap);
    va_end(ap);
    va_start(ap, fmt);
    vfprintf(file, fmt, ap);
    va_end(ap);
}

Upvotes: 3

ern0
ern0

Reputation: 3172

If you're using Unix (BSD/Linux/Solaris/etc.), maybe it's easier to use tee for that.

Upvotes: 0

Ameliorator
Ameliorator

Reputation: 437

I think this should work ->

#define PTF(A,...) fprintf(file,A,##__VA_ARGS__); printf(A,##__VA_ARGS__);

int y = 9;
PTF("\nRound %d \n",y);

Variadic Macros link - http://gcc.gnu.org/onlinedocs/cpp/Variadic-Macros.html

Upvotes: 0

tangrs
tangrs

Reputation: 9930

Change

#define PTF(A,y) fprintf(file,"%s",A,y);printf("%s %d",A,y);

to

#define PTF(A,y) fprintf(file,A,y);printf("%s %d",A,y);

Note:

PTF("Round %d",9); will have fprint write Round 9 to the file but printf will still show Round %d 9.

You'll also have to make sure you only specify one specifier to fprintf

Upvotes: 1

Related Questions