Is there any way to find out the number of variational function arguments specific to Visual C ++?

Firstly, there is no portable way to calculate the length va_list. Perhaps there is a way to do this in a debug (not optimized) Visual C ++ configuration?

In particular, I have a variational function:

void MyVariadic( const char* format, ... )
{
}

(and I can’t change the signature), and I want to detect cases where it formatcontains percentage characters and the argument list is empty (which probably means that someone passed any line directly formatinstead of using %s), and as soon as I find such cases, I can assert()or something like that.

Is there a way to do this in a non-optimized debug build in Visual C ++?

+3
source share
3 answers

Since you agree with specific Visual C ++ solutions, and if your goal is to help detect inconsistent printf lines, consider using SAL Annotations . The build that you run with code analysis enabled will report errors if the format string and arguments do not match.

Annotations you want - _Printf_format_string_. Take a look at how printfannotated in stdio.hfor inspiration.

Consider the following code:

int i = 12;
printf("%d %s", i);

Visual C ++ 2013 works with code analysis reports for me

C6063 There is no string argument 'printf' that matches the qualifier '2'.

+4
source

(From comments)

MyVariadic(str), str - const char[], . void MyVariadic(const char*, ...), . void MyVariadic(const char*) - .

void MyVariadic(const char* str) void MyVariadic(const char*, ...). , &MyVariadic void (*p)(const char*, ...), const char* , printf. , MyVariadic("%s", str).

+2

- ( ):

#define COUNT_N(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...)    N
#define COUNT(...)   COUNT_N(__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
// Warning: COUNT() return 1 (as COUNT(A)) :-/
#define ARG1(S, ...) S

- :

#define MyVariadic_And_Check(...) do { \
    Check(ARG1(__VA_ARGS__), COUNT(__VA_ARGS__) - 1); \
    MyVariadic(__VA_ARGS__); } while(false) 

Check(const char* format, int count) .
. MyVariadic const char* format, COUNT .

++ 11 - :

template <typename ... Args>
void MyVariadic_And_Check(const char* format, Args&&...args);

to check the quantity and type.

0
source

All Articles