Examples explain the use of variable parameters and default parameters in C + + functions _c language

Source: Internet
Author: User

A function that contains a list of variable arguments
if the last member in the function declaration is an ellipsis (...), the function declaration can take a variable number of arguments. In these cases, C + + only provides type checking for explicitly declared parameters. Even if the number and type of parameters are variable, you can use the variable argument list when you need to generalize the function. The series of functions is an example of a function that uses a variable argument list. Printfargument-declaration-list
Functions that contain variable arguments
To access the declared arguments, use the stdarg containing the standard include file. The macros in H (described below).

A function declaration that takes a variable number of arguments requires at least one placeholder parameter (even if it is not used). If you do not supply this placeholder parameter, you cannot access the remaining parameters.
When the parameters of the char type are passed as variable arguments, they are converted to the int type. Similarly, when the parameters of a float type are passed as variable arguments, they are converted to the double type. Other types of parameters are limited by common integer and floating-point elevation.

Use the ellipsis (...) in the argument list to declare a function that requires a list of variables. Used in Stdarg. H contains the types described in the file and the parameters passed by the macro access variable list. For more information about these macros, see Va_arg, Va_copy, Va_end, Va_start. (In the C Run-time Library document).
The following example shows how to use a macro with a type (in Stdarg. H in the statement): Va_listva_endva_argva_start

Variable_argument_lists.cpp #include <stdio.h> #include <stdarg.h>//declaration, but not definition, of
Showvar.
void Showvar (char *sztypes, ...);

int main () {Showvar ("Fcsi", 32.4f, ' a ', "Test string", 4);} Showvar takes a format string of the the form//"IFCS" where each character specifies the '//type of ' the argument in th
At position. i = int//F = float//c = char//s = string (char *)////Following the format specification is a variable//l ist of arguments. Each argument corresponds to//a format character in the format string to which//the sztypes parameter points void S Howvar (char *sztypes, ...)
  {va_list VL;

  int i; Sztypes is the last argument specified;
  You are must access//all others using the Variable-argument macros.

  Va_start (VL, sztypes);
  Step through the list.
     for (i = 0; sztypes[i]!= '; ++i ') {Union printable_t {int i;
     float F;
     char c;
   Char *s;

   } printable;Switch (Sztypes[i]) {//Type to expect.
      Case ' I ': printable.i = Va_arg (VL, int);
     printf_s ("%i\n", printable.i);

     Break
       Case ' f ': Printable.f = Va_arg (VL, double);
     printf_s ("%f\n", PRINTABLE.F);

     Break
       Case ' C ': printable.c = Va_arg (VL, Char);
     printf_s ("%c\n", printable.c);

     Break
       Case ' s ': PRINTABLE.S = Va_arg (VL, char *);
     printf_s ("%s\n", PRINTABLE.S);

     Break
   Default:break;
} va_end (VL);

 }//output://32.400002//A//Test string

The previous example demonstrates the following important concepts:
Before accessing any variable parameters, you must establish a list tag as a variable of type va_list. In the previous example, the tag is called VL.
Use the VA_ARG macro to access individual parameters. You must tell the VA_ARG macro the type of parameter you want to retrieve so that it can transmit the correct number of bytes from the stack. If the type specified for Va_arg is different from the type provided by the calling program, the result is unpredictable.
The results obtained using the VA_ARG macro should be explicitly cast to the desired type.
You must call the macro to terminate the variable parameter processing. Va_end


Default Parameters
in many cases, a function has parameters that are not used frequently because it is sufficient to use the default value. To resolve this issue, the default parameter tool allows you to specify only the parameters that are meaningful in a given call for a function. To illustrate this concept, consider the example shown in the function overload.

Prototype three print functions.
int print (char *s);         Print a string.
int print (double dvalue);      Print a double.
int print (double dvalue, int prec); Print a double with a
//given precision.

In many applications, you can provide a reasonable default value for PREC, eliminating the need for two functions:

Prototype two print functions.
int print (char *s);          Print a string.
int print (double dvalue, int prec=2); Print a double with a
//given precision.

The

Changes the implementation of the print function slightly to reflect the fact that there is only one such function in the type double:

//default_arguments.cpp//compile with:/ehsc/c//Print a double in specified precis
Ion. Positive numbers for precision indicate I many digits//precision after the decimal point to show.

Negative//numbers for precision indicate where to round the number/to the "the" the decimal point.

#include <iostream> #include <math.h> using namespace std;
  int print (double dvalue, int prec) {//Use Table-lookup for rounding/truncation. static const double rgpow10[] = {10E-7, 10E-6, 10E-5, 10E-4, 10E-3, 10E-2, 10E-1, 10E0, 10E1, 10E2, 10E3, 10E4,
  10E5, 10E6};
  const int Ipowzero = 6;
  If precision out of range, just print the number.
   if (Prec >=-6 && prec <= 7)//Scale, truncate, then Rescale.
  Dvalue = Floor (Dvalue/rgpow10[ipowzero-prec]) * RGPOW10[IPOWZERO-PREC];
  cout << dvalue << Endl;
return Cout.good (); }

To invoke the new print function, use the following code:

Print (d);  Precision of 2 supplied by default argument.
Print (d, 0); Override default argument to achieve the other
//results.

When using default parameters, be aware of the following points:
The default parameters are used only in function calls where the trailing parameters are omitted-they must be the last argument. Therefore, the following code is illegal:

int print (Double dvalue = 0.0, int prec);

The default parameters cannot be redefined in future declarations, even if the redefined parameters are the same as the original parameters. Therefore, the following code generates an error:

Prototype for print function.
int print (double dvalue, int prec = 2);

...

The Definition for print function.
int print (double dvalue, int prec = 2)
{
...
}

The problem with this code is that the function declarations in the definition redefine the default parameters of the Prec.
Future declarations can add additional default parameters.
You can provide a default parameter for pointers to functions. For example:

Int (*pshowintval) (int i = 0);

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.