使用预处理宏
#define sum(...) \
_sum(sizeof((int []){ __VA_ARGS__ }) / sizeof(int), (int []){ __VA_ARGS__ })
使用sum(1,2,3) 调用时,该行被翻译(一个简单的字符串替换,将"__VA_ARGS__" 替换为"1,2,3")为:
_sum(sizeof((int []){1,2,3}) / sizeof(int), (int []){1,2,3})
这是对_sum() 的函数调用,传递了两件事:
- 数组 {1,2,3} 中的整数个数为 3(它通过将三整数数组的大小除以单个整数的大小得到)。
- 指向数组本身的指针(或包含相同值的完全不同的数组,具体取决于您的编译器的智能程度)。
_sum() 函数所做的只是将每个整数添加到s(最初为零),直到计数用完。
上面的第一个要点有一些解释。当您有一个由N 元素组成的数组时,定义如下:
tType x[22];
数组的大小是sizeof(x),即所有元素的大小。该数组的单个元素的大小是sizeof(x[0]),即第一个元素的大小,尽管我通常更喜欢sizeof(*x) 变体。
因此,要计算元素的数量,您只需将总大小除以元素的大小,使用以下方法之一:
sizeof(x) / sizeof(x[0])
sizeof(x) / sizeof(*x)
而且,既然您要求对代码进行详细分析,那么我们开始吧:
// 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).
}