📄 va_arg.html
字号:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head> <meta name="generator" content= "HTML Tidy for Linux/x86 (vers 1 September 2005), see www.w3.org"> <title>va_arg</title> <link href="../cppreference.css" rel="stylesheet" type="text/css"></head><body><table> <tr> <td> <div class="body-content"> <div class="header-box"> <a href="../index.html">cppreference.com</a> > <a href= "index.html">Other Standard C Functions</a> > <a href= "va_arg.html">va_arg</a> </div> <div class="name-format"> va_arg </div> <div class="syntax-name-format"> Syntax: </div> <pre class="syntax-box"> #include <stdarg.h> type va_arg( <strong>va_list</strong> argptr, type ); void va_end( <strong>va_list</strong> argptr ); void va_start( <strong>va_list</strong> argptr, last_parm );</pre> <p>The va_arg() macros are used to pass a variable number of arguments to a function.</p> <ol> <li>First, you must have a call to va_start() passing a valid <strong>va_list</strong> and the mandatory first argument of the function. This first argument can be anything; one way to use it is to have it be an integer describing the number of parameters being passed.</li> <li>Next, you call va_arg() passing the <strong>va_list</strong> and the type of the argument to be returned. The return value of va_arg() is the current parameter.</li> <li>Repeat calls to va_arg() for however many arguments you have.</li> <li>Finally, a call to va_end() passing the <strong>va_list</strong> is necessary for proper cleanup.</li> </ol> <p>For example:</p> <pre class="example-code"> int sum( int num, ... ) { int answer = 0; <strong>va_list</strong> argptr; va_start( argptr, num ); for( ; num > 0; num-- ) { answer += va_arg( argptr, int ); } va_end( argptr ); return( answer ); } int main( void ) { int answer = sum( 4, 4, 3, 2, 1 ); printf( "The answer is %d\n", answer ); return( 0 ); } </pre> <p>This code displays 10, which is 4+3+2+1.</p> <p>Here is another example of variable argument function, which is a simple printing function:</p> <pre class="example-code"> void my_printf( char *format, ... ) { <strong>va_list</strong> argptr; va_start( argptr, format ); while( *format != '\0' ) { // string if( *format == 's' ) { char* s = va_arg( argptr, char * ); printf( "Printing a string: %s\n", s ); } // character else if( *format == 'c' ) { char c = (char) va_arg( argptr, int ); printf( "Printing a character: %c\n", c ); break; } // integer else if( *format == 'd' ) { int d = va_arg( argptr, int ); printf( "Printing an integer: %d\n", d ); } *format++; } va_end( argptr ); } int main( void ) { my_printf( "sdc", "This is a string", 29, 'X' ); return( 0 ); } </pre> <p>This code displays the following output when run:</p> <pre class="example-code"> Printing a string: This is a string Printing an integer: 29 Printing a character: X </pre> </div> </td> </tr> </table></body></html>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -