0

Can't get right amount of arguments passes to function call

I have tried to use macros to get exact amount of arguments and it seems gets wrong when I call the function w/o arguments at all.

#include <stdio.h>
#define _ARG2(_0, _1, _2, ...) _2
#define NARG2(...) _ARG2(__VA_ARGS__, 2, 1, 0)

int main (void){
    printf ("The result of NARG2() is %d\n",NARG2());//1?
    return 0;
}

I expect NARG2 outputs 0

  • ‘I expect NARG2 outputs 0’ Why? You pass 1 to _2 in your example. – j3141592653589793238 Jun 20 '19 at 15:18
  • 1
    Possible duplicate of [How to count the number of arguments passed to a function that accepts a variable number of arguments?](https://stackoverflow.com/questions/4421681/how-to-count-the-number-of-arguments-passed-to-a-function-that-accepts-a-variabl) – ooj-001 Jun 20 '19 at 15:19
  • 1
    Possible duplicate of [How to count the number of arguments passed to a function that accepts a variable number of arguments?](https://stackoverflow.com/questions/4421681/how-to-count-the-number-of-arguments-passed-to-a-function-that-accepts-a-variabl) – j3141592653589793238 Jun 20 '19 at 15:20
  • 1
    @ooj-001 Dont write the comment by hand; you need to __flag__ the question as duplicate. – j3141592653589793238 Jun 20 '19 at 15:22
  • You probably can't do this. It's generally considered to be a bad idea in C. Is this a puzzle you're trying to solve for its own sake, or is there a practical reason you need to count arguments? If it's a puzzle, then puzzle away, but if it's a practical problem, I strongly urge you to rethink your requirements so that you don't have to try to count arguments in this way. – Steve Summit Jun 20 '19 at 15:55
  • That solution above won't work properly if with passing no arguments at all. Just want to consider that function will not fail when caller forgets to pass the arguments – Taras Ivashchuk Jun 20 '19 at 16:24

0 Answers0