這個問題困惑我有些時間了..
早期我想知道 printf、scanf 中間的 %s, %c, %d... 一堆是怎麼寫的,
後來在翻 C++ 字典的時候有翻到相似的函數,
va_start, va_end, va_arg,與其說是函數,
到不如說是 macro 會好些

在寫副函式的時候往往會遇到一個問題,

double foo1(double x1);
double foo2(double x1, double x2);
double foo3(double x1, double x2, double x3);
..... 

如果今天是要寫到 foo5...那就不用再說下去了吧 = =
當然是可以有其它方式完成,
不過特別介紹這種不定參數的方式
例子中使用的 function 是用來加總使用者的輸入整數
當然也可以配合字串去完成,
簡單的 sample code 如下...

// ================================
// FileName: Argc.cpp
// Author:   Edison.Shih.
// Complier: VC 6.0

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h> // use instruction va_list, va_start, va_end...


int foo(int n,...); // cal the sum of param.

// ================================
int main(int argc, char **argv)
{
        printf("sum of (1,2,3,4,5,6,7,8,9,10) = %d\n", foo(10, 1,2,3,4,5,6,7,8,9,10));
        return 0;
}

// ================================
int foo(int n,...){
        va_list list_ptr;
        va_start(list_ptr, n);
        int sum = 0;
       
        for(int i=0; i<n; i++){
                sum += va_arg(list_ptr, int);
        }
        va_end(list_ptr);
        return sum;
}

arrow
arrow
    全站熱搜

    Edison 發表在 痞客邦 留言(0) 人氣()