OiO.lk Blog C++ Why does my variadic macro throw an error when nothing is passed?
C++

Why does my variadic macro throw an error when nothing is passed?


Here’s a more structured and formatted version of your question for Stack Overflow. I’ve included necessary details and explanations according to their question guidelines:


Title: Why does my variadic macro throw an error when nothing is passed?

Body:

I’m trying to create a C program that takes multiple integers as input via the print(...) macro, without needing to pass the length of arguments manually from the main function. To achieve this, I implemented a macro to automatically determine the number of arguments passed and then print them.

Here’s the code:

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

void function_for_printing(int len, ...)
{
    va_list args;
    va_start(args, len);
    if (len > 0)
    {
        for (int i = 0; i < len; i++)
        {
            int temp = va_arg(args, int);
            printf("%d ", temp);
        }
        va_end(args);
        printf("\n");
    }
    else
    {
        va_end(args);
        printf("\nNothing passed\n");
        return;
    }
    printf("\n");
    return;
}

#define print(...) ({\
    int array[]= {__VA_ARGS__};\
    int size = sizeof(array)/sizeof(array[0]);\
    if(size==0)\
    {\
        function_for_printing(0);\
    }\
    else if (size!=0)\
    {\
        function_for_printing(size, __VA_ARGS__);\
    }\
})

int main()
{
    print(1, 2, 4); // works fine
    print(1, 2, 3, 4, 5, 6, 7); // works fine
    print(); // throws an error

    return 0;
}

My objective:

I want the print(...) macro to:

  1. Automatically determine the number of arguments passed (without explicitly passing the size).
  2. Print the arguments using function_for_printing(int, ...).
  3. If no arguments are passed, the macro should print "Nothing passed" without throwing an error.

Issue:

When no arguments are passed to print(), the program throws an error during compilation. I expected the program to handle an empty input by printing "Nothing passed". I understand that __VA_ARGS__ can cause problems when no arguments are passed.

What I tried:

  1. I typecasted __VA_ARGS__ into an int[].
  2. I calculated the length using sizeof(array)/sizeof(array[0]).
  3. Based on the length, I either pass the arguments to function_for_printing() or call it with 0 if the length is zero.
  4. When the length is zero, I wanted it to handle the case gracefully, but the macro doesn’t seem to support empty __VA_ARGS__ as expected.

Question:

How can I modify my code or macro to handle cases where no arguments are passed to print(...) without causing errors?

Any guidance would be appreciated! Thanks in advance.



You need to sign in to view this answers

Exit mobile version