I understand this code calculates the sum of the args of a variable, however, I don’t understand how it works. It looks really abstract to me. Can someone explain how the below works?
Thanks!
#include <stdio.h>
#define sum(...) \
_sum(sizeof((int []){ __VA_ARGS__ }) / sizeof(int), (int []){ __VA_ARGS__ })
int _sum(size_t count, int values[])
{
int s = 0;
while(count--) s += values[count];
return s;
}
int main(void)
{
printf("%i", sum(1, 2, 3));
}
With the pre-processor macro
being called with
sum(1,2,3), the line is translated (a simple string substitution, replacing"__VA_ARGS__"with"1,2,3") into:which is a function call to
_sum()passing two things:All the
_sum()function does is add each of the integers tos(which is initially zero) until the count runs out.That first bullet point above bears some explanation. When you have an array of
Nelements defined as follows:the size of the array is
sizeof(x), the size of all elements. The size of a single element of that array issizeof(x[0]), the size of the first element, although I often prefer thesizeof(*x)variant.So, to count the number of elements, you simply divide the total size by the size of an element, using one of the following:
And, since you’ve asked for a detailed analysis of the code, here we go: