C標準庫源碼解讀(VC9.0版本)——stdarg.h

來源:互聯網
上載者:User

      stdarg.h中定義處理可變參數函數的方法。我們常用的printf,scanf等函數,都是以此做處理的,平時寫代碼的時候很少使用到,但是學習多一種方法,明白更多使用方法。其實變參數的實現是通過編譯時間參數壓入棧的位置去尋找的。而正確處理需要給出對應的結構類型,因為需要根據結構大小取資料值。明白了這個原理,理解並寫處理不定參數的函數並不難。

Variable arguments handling

This header defines macros to access the individual arguments of a list of unnamed arguments whose number and types are not known to the called function.

A function may accept a varying number of additional arguments without corresponding parameter declarations by including a comma and three dots (,...) after its regular named parameters:

return_type function_name ( parameter_declarations , ... );
To access these additional arguments the macros
va_start, va_arg and
va_end, declared in this header, can be used:

  • First, va_start initializes the list of variable arguments as ava_list.
  • Subsequent executions of va_arg yield the values of the additional arguments in the same order as passed to the function.
  • Finally, va_end shall be executed before the function returns.
Types
va_list
Type to hold information about variable arguments (type )
Macro functions
va_start
Initialize a variable argument list (macro )
va_arg
Retrieve next argument (macro )
va_end
End using variable argument list (macro )
va_copy
Copy variable argument list (macro )

 

#include <stdarg.h>#include <assert.h>/* type definitions */typedef struct {char c;} Cstruct;int tryit(char * format,...){int ctr = 0;va_list ap;va_start(ap,format);while (*format){switch(*format){case 'i' :assert (va_arg(ap, int) == ++ctr);break;case 'd' :assert (va_arg(ap, double) == ++ctr) ;break;case 'p' :assert (va_arg(ap, char *)[0] == ++ctr);break;case 's' :assert (va_arg(ap, Cstruct).c == ++ctr);}}va_end(ap);return ctr;}int main (){Cstruct stu;stu.c = 'a';int k = tryit("dip",1.0,10,"str",stu);return 0;}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.