Making your own printf like functions

Hello. I have currently made a function which is declared as follows:

inline void fdebugPrintf(FILE* file, const char* fmt, ...){
#ifdef _DEBUG
fprintf(file, fmt);
#endif
}

It works perfectly fine it's just that when I use it like this:

fprintf(log, "total world point: <%f, %f>.", 2.0f, 2.0f);

the result in the file named log looks like this:

total world point: <0.0f, 0.0f>.

The problem is that the function I made does not use the ... I specified. Does anybody know how to make the function use this?
If you look closely, you'll see that you're not really passing any parameters to fprintf() other than the FILE * and the format string.

The C library provides the interface to deal with additional arguments: http://www.cplusplus.com/reference/clibrary/cstdarg/

This really doesn't seem like a good idea, though.
You want to pass a variable number of arguments to a function which is ok, but it has a quirky syntax.

The idea is that a C function pushes all it's arguments, makes the function call, then pops all the arguments. This means that the caller knows how many there are. If the called function wants to allow this, it uses the ... syntax to say so.

For example,
 
int kbwTrace(const char *fmt, ...);


The next bit is the syntax to support access to these args, these are va_list and va_start.

Putting the whole thing together, you get:
1
2
3
4
5
6
7
8
9
10
11
12
#include <stdargs.h>

int kbwTrace(const char *fmt, ...)
{
#ifndef NDEBUG
    va_list args;
    va_start(args, fmt);
    return printf(fmt, args);
#else
    return 0;
#endif
}


A final word, DEBUG is usually defined by a vendor, but the standard says NDEBUG.
Just to add... ellipsis is generally anti-C++.
You mean like goto or multiple inheritance?

C++ is a multi-paradigm language. It has a number of features that are all there for a reason.

For example, although C++ supports Object Orientation, you don't have to write OO programs in C++. Take STL for example, it's not Object Oriented.

You use the features that are suitable for your design/pattern/paradigm. Nothing is black-listed.

Using variable number of args may be anti-OO, but it's not anti-C++.
Using variable number of args may be anti-OO, but it's not anti-C++.

Yes, it is. It isn't type-safe, it is needlessly redundant, and C++ provides better means to achieve the same effect (depending on the actual problem that might be virtual functions, function pointers, overloading, streams, ...). Or do you really think that you know the types you pass better than your compiler?
It has a number of features that are all there for a reason

Some features are in C++ just for compatibilty with C
Topic archived. No new replies allowed.