1

I want to print output if OUT is 1. So i think that code.

#define OUT 1

void d_printf(char *text){
  if(OUT)
    printf("%s", text);
}

int main(void){
  d_printf("%d\n", 5);
  return 0;
}

But my parametre is char*, i can't send %d, 5. How can i solve this?

hundnum
  • 145
  • 2
  • 8
  • One way is to change `d_printf` to accept variable length arguments and then pass those straight through to [vprintf](https://linux.die.net/man/3/vfprintf). – kaylum Jan 04 '21 at 21:49
  • Does this answer your question? [Passing variable number of arguments around](https://stackoverflow.com/questions/205529/passing-variable-number-of-arguments-around) – kaylum Jan 04 '21 at 21:52
  • 1
    Another solution is to allocate a string buffer, use `snprintf` to create a string in that buffer with the desired output and then pass that buffer to `d_printf`. – kaylum Jan 04 '21 at 21:53

1 Answers1

1

You can use a simple macro:

#include <stdio.h>

#define OUT 1

#define d_printf  OUT && printf

int main(void) {
    d_printf("%d\n", 5);
    return 0;
}

If you get compiler warnings about an unused expression, you can use a more elaborate macro:

#include <stdio.h>

#define OUT 1

#define d_printf(...)  do { if (OUT) printf(__VA_ARGS__); } while(0)

int main(void) {
    d_printf("%d\n", 5);
    return 0;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189