Getting varargs size in C?

I am trying to convert Java code to C. Java code is as follows:

public static int minimum( int... minimum ) {

    assert( minimum.length > 0 );

    if ( minimum.length > 0 )
     .... // some code that i am able to translate to C without any hassle
}

Now I understand how to have varargs in C using the header stdarg.hand using the provided macros. However, I am stuck doing the part minimum.length.

I tried strlen, but the terminal gives me an incompatible integer to prevent pointer conversion. Is there a way in C where I can replicate the same as Java?

+4
source share
2 answers

Not directly, as pointed out by @MichaelBurr, you need to pass the number of elements or use the sentinel.

An indirect way to do this is to use complex literals:

#include <stdio.h>
#include <stdarg.h>
#include <limits.h>

#define minimum(...) fnminimum(sizeof((int []) {__VA_ARGS__}) / sizeof(int), __VA_ARGS__)

static int fnminimum(int n, ...)
{
    int num, min = INT_MAX;
    va_list ap;

    va_start(ap, n);
    while (n--) {
        num = va_arg(ap, int);
        if (num < min) {
            min = num;
        }
    }
    va_end(ap);
    return min;
}

int main(void)
{
    int a = 1;

    printf("%d\n", minimum(2, 30, 7, a++, 4));
    return 0;
}

() NARGS ( N ):

#include <stdio.h>
#include <stdarg.h>
#include <limits.h>

#define NARGS_SEQ(_1,_2,_3,_4,_5,_6,_7,_8,_9,N,...) N
#define NARGS(...) NARGS_SEQ(__VA_ARGS__, 9, 8, 7, 6, 5, 4, 3, 2, 1)

#define minimum(...) fnminimum(NARGS(__VA_ARGS__), __VA_ARGS__)

static int fnminimum(int n, ...)
{
    int num, min = INT_MAX;
    va_list ap;

    va_start(ap, n);
    while (n--) {
        num = va_arg(ap, int);
        if (num < min) {
            min = num;
        }
    }
    va_end(ap);
    return min;
}

int main(void)
{
    printf("%d\n", minimum(2, 30, 7, 1, 4));
    return 0;
}

:

1
+5

vararg, C.

:

  • ,
  • ( printf() )
  • (, NULL 0), vararg

, __VA_ARGS__, varargs .

+2

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


All Articles