top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

C: Counting the number of arguments in __VA_ARGS__

+2 votes
797 views

Is there a way to count the number of variadic macro arguments in C?

I found a way to check if the list is empty: examine sizeof(STR((__VA_ARGS__))) where STR is a macro that stringifies its argument. If it is 3, __VA_ARGS__ is empty. I wonder if there is a less hackish approach.

The macro arguments are expressions, but not of a uniform type, so an array-based approach does not work.

posted Dec 12, 2013 by Seema Siddique

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote
#define PP_NARG( ...) PP_NARG_(__VA_ARGS__,PP_RSEQ_N())
#define PP_NARG_(...) PP_ARG_N(__VA_ARGS__)
#define PP_ARG_N(_1,_2,_3,_4,_5,_6,_7,_8,_9,[..],_61,_62,_63,N,...) N
#define PP_RSEQ_N() 63,62,61,60,[..],9,8,7,6,5,4,3,2,1,0

PP_NARG(A) 1
PP_NARG(A, B) 2
answer Dec 12, 2013 by anonymous
Looks that this returns the 64th argument if the argument list is longer than 63. I don't want to silently produce wrong results if some arbitrary limit is exceeded.
Similar Questions
+1 vote

Does there exist any way to make the command line arguments available to other functions without passing them as arguments to the function in C programming?

+2 votes

Words may be separated by any amount of whitespace characters. There can be integers in a file, but the program should only count words which have at least one alphabetic character.

+1 vote

Given an array of 1s and 0s which has all 1s first followed by all 0s. Find the number of 0s. Count the number of zeroes in the given array.

+1 vote

double the number of vowels in a given string using c programming language
Ex:
Given String="Maven"
Output Required="Maaveen".

...