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));
}
Run Code Online (Sandbox Code Playgroud)
pax*_*blo 21
使用预处理器宏
#define sum(...) \
_sum(sizeof((int []){ __VA_ARGS__ }) / sizeof(int), (int []){ __VA_ARGS__ })
Run Code Online (Sandbox Code Playgroud)
被调用时sum(1,2,3),行被转换(简单的字符串替换,替换"__VA_ARGS__"为"1,2,3"):
_sum(sizeof((int []){1,2,3}) / sizeof(int), (int []){1,2,3})
Run Code Online (Sandbox Code Playgroud)
这是一个函数调用_sum()传递两件事:
所有_sum()函数都是将每个整数添加到s(最初为零),直到计数用完为止.
上面的第一个要点有一些解释.如果您有一个N如下定义的元素数组:
tType x[22];
Run Code Online (Sandbox Code Playgroud)
所述的尺寸数组是sizeof(x),所有元件的尺寸.该数组的单个元素sizeof(x[0])的大小是第一个元素的大小,尽管我经常更喜欢该sizeof(*x)变体.
因此,要计算元素的数量,只需使用以下之一将总大小除以元素的大小:
sizeof(x) / sizeof(x[0])
sizeof(x) / sizeof(*x)
Run Code Online (Sandbox Code Playgroud)
而且,既然您已经要求对代码进行详细分析,那么我们开始:
// Needed for printf().
#include <stdio.h>
// Macro to convert sum(n1,n2,...,nN) to _sum(N,n1,n2,...,nN).
// This calculates the length of the array by dividing its size by the size
// of an int and passes both the length and array through to the new
// function.
// __VA_ARGS__ is replaced with the entire marcro argument list, '1,2,3' in
// this case.
#define sum(...) \
_sum(sizeof((int []){ __VA_ARGS__ }) / sizeof(int), (int []){ __VA_ARGS__ })
// Function to take size and pointer to int array, and return sum.
int _sum (size_t count, int values[]) {
int s = 0; // Initial sum of zero.
while(count--) // Until elements exhausted (count down).
s += values[count]; // Add each array element to accumulator.
return s; // Return sum.
}
int main (void) {
printf ("%i", sum(1, 2, 3)); // Test it with 1, 2 and 3 (should print 6).
}
Run Code Online (Sandbox Code Playgroud)