Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      va_arg

      From cppreference.com
      <cpp‎ |utility‎ |variadic
       
       
      Utilities library
       
       
      Defined in header<cstdarg>
      T va_arg( std::va_list ap, T);

      Theva_arg macro expands to an expression of typeT that corresponds to the next parameter from theva_listap.

      Prior to callingva_arg,ap must be initialized by a call to eitherva_start orva_copy, with no intervening call tova_end. Each invocation of theva_arg macro modifiesap to point to the next variable argument.

      If the type of the next argument inap (after promotions) is notcompatible withT, the behavior is undefined, unless:

      • one type is a signed integer type, the other type is the corresponding unsigned integer type, and the value is representable in both types; or
      • one type is pointer tovoid and the other is a pointer to a character type (char,signedchar, orunsignedchar).

      Ifva_arg is called when there are no more arguments inap, the behavior is undefined.

      Contents

      [edit]Parameters

      ap - an instance of theva_list type
      T - the type of the next parameter inap

      [edit]Expanded value

      The next variable parameter inap.

      [edit]Example

      Run this code
      #include <cstdarg>#include <cstdio>#include <iostream> void print_variance(std::size_t count,constchar* fmt, ...){double sum=0;double sum_sq=0;    std::va_list args;va_start(args, fmt);for(std::size_t i= count; i--;){double num= va_arg(args,double);        sum+= num;        sum_sq+= num*num;}va_end(args);std::printf(fmt, sum_sq/ count-(sum/ count)*(sum/ count));} void nano_printf(constchar* fmt, ...){    std::va_list args;va_start(args, fmt); for(constchar* p= fmt;*p!='\0';++p){switch(*p){case'%':switch(*++p)// read format symbol{case'i':std::cout<< va_arg(args,int);continue;case'f':std::cout<< va_arg(args,double);continue;case's':std::cout<< va_arg(args,constchar*);continue;case'c':std::cout<<static_cast<char>(va_arg(args,int));continue;case'%':std::cout<<'%';continue;/* ...more cases... */}break;// format error...case'\n':std::cout<<'\n';continue;case'\t':std::cout<<'\t';continue;/* ...more cases... */}std::cout<<*p;} va_end(args);} int main(){    print_variance(4,"%f\n",25.0,27.3,26.9,25.7);    nano_printf("Args: %i%% %c%f %s\n",42,'#',3.14,"C++");}

      Output:

      0.846875Args: 42% #3.14 C++

      [edit]See also

      enables access to variadic function arguments
      (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]
      C documentation forva_arg
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/utility/variadic/va_arg&oldid=179735"

      [8]ページ先頭

      ©2009-2025 Movatter.jp