Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      Variadic functions

      From cppreference.com
      <cpp‎ |utility
       
       
      Utilities library
       
       

      Variadic functions are functions (e.g.std::printf) which take avariable number of arguments.

      To declare a variadic function, an ellipsis appears after the list of parameters, e.g.int printf(constchar* format...);, which may be preceded by an optional comma. SeeVariadic arguments for additional detail on the syntax, automatic argument conversions and the alternatives.

      To access the variadic arguments from the function body, the following library facilities are provided:

      Defined in header<cstdarg>
      enables access to variadic function arguments
      (function macro)[edit]
      accesses the next variadic function argument
      (function macro)[edit]
      (C++11)
      makes a copy of the variadic function arguments
      (function macro)[edit]
      ends traversal of the variadic function arguments
      (function macro)[edit]
      holds the information needed byva_start,va_arg,va_end, andva_copy
      (typedef)[edit]

      [edit]Example

      Run this code
      #include <cstdarg>#include <iostream> void simple_printf(constchar* fmt...)// C-style "const char* fmt, ..." is also valid{va_list args;va_start(args, fmt); while(*fmt!='\0'){if(*fmt=='d'){int i=va_arg(args,int);std::cout<< i<<'\n';}elseif(*fmt=='c'){// note automatic conversion to integral typeint c=va_arg(args,int);std::cout<<static_cast<char>(c)<<'\n';}elseif(*fmt=='f'){double d=va_arg(args,double);std::cout<< d<<'\n';}++fmt;} va_end(args);} int main(){    simple_printf("dcff",3,'a',1.999,42.5);}

      Output:

      3a1.99942.5

      [edit]See also

      C documentation forVariadic functions
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/utility/variadic&oldid=168365"

      [8]ページ先頭

      ©2009-2025 Movatter.jp