Help with my printf function

For debugging purposes, I would like to have a printf_debug function that will function exactly the same as the standard printf function, but will only print if #DEFINE DEBUG is true

I know that I need to use varagrs (...), but I have no idea how to achieve this.

Thanks in advance.

+3
source share
5 answers

It’s easier just to #define it. Something like that:

#ifdef DEBUG
#define printf_debug printf
#else
#define printf_debug while(0)printf
#endif
+9
source

I do not understand what you want to achieve. If you want the code block to be executed only if DEBUGdefined, use the preprocessor directive #ifdef.

#include <stdio.h>
#include <stdarg.h>
#define DEBUG

void printf_debug(const char *format, ...) {
  #ifdef DEBUG
  va_list args;
  va_start(args, format);
  vprintf(format, args);
  va_end(args);
  #endif /* DEBUG */
}
+2
source

vargs, . , :

#ifdef DEBUG
#define printf_debug(fmt, args...) printf("%s[%d]: "fmt, __FUNCTION__, __LINE__, ##args)
#else
#define printf_debug(fmt, args...)
#endif

## args, , vargs .

+2

va_arg, . : http://www.cppreference.com/wiki/c/other/va_arg. ++, C.

#ifdef.

printf, DEBUG, #define, .

0

C99!

#include <stdio.h>

#define DEBUG

#ifdef DEBUG
 #define debug(...) printf(__VA_ARGS__)
#else
 #define debug while(0)
#endif

int main(int argc, char *argv[])
{
    debug("Only shows when DEBUG is defined!\n");
    return 0;
}

varidic , :

#include <stdio.h>

#define DEBUG

#ifdef DEBUG
 #define debug printf
#else
 #define debug while(0)
#endif

int main(int argc, char *argv[])
{
    debug("Only shows when DEBUG is defined!\n");
    return 0;
}

, stderr, stdout, :

#include <stdio.h>

#define DEBUG

#ifdef DEBUG
 #define debug(...) fprintf(stderr, __VA_ARGS__)
#else
 #define debug while(0)
#endif

int main(int argc, char *argv[])
{
    debug("Only shows when DEBUG is defined!\n");
    return 0;
}
0
source

Source: https://habr.com/ru/post/1747060/


All Articles