Stdarg. h usage Summary

Source: Internet
Author: User

Today, I was bored with the computing method lesson, so I took a look at the C ++ programming path .. I accidentally saw # include <stdarg. h> va_list, va_start, va_end and other things. I don't know how to use them, so I really want to solve them ..

After class, go back to the dormitory and check the computer to see if it is a pointer defined as a variable parameter list:

So I wrote down the following small program for use (the development environment is vs2005)


  

# Include <iostream>

# Include <stdarg. h>

 

Const int n = 5;

Using namespace STD;

 

Void stdarg (INT A1 ,...)

{

Va_list argp;

Int I;

Int ary [N];

 

Va_start (argp, A1 );

Ary [0] = A1;

For (I = 1; I <n; I ++)

Ary [I] = va_arg (argp, INT );

Va_end (argp );

For (I = 0; I <n; I ++)

Cout <ary [I] <Endl;

}

 

Void main ()

{

Stdarg (5, 12, 64, 34, 23 );

}

I don't need to talk about the running result ..

 

If you want to learn more, read the following article, hoping to help you!

In C language programming, we will encounter some functions with variable parameter numbers, such as printf ()
This function is defined as follows:
Int printf (const char * format ,...);
Besides the fixed format parameter, the following parameter numbers and types are
Variable. For example, we can have the following different call methods:
Printf ("% d", I );
Printf ("% s", S );
Printf ("the number is % d, string is: % s", I, S );
How to write the c Functions of variable parameters and how the function compilers of these variable parameters are implemented?
What about now? This article will discuss this issue and hope to help you.
Users know that these problems do not exist in C ++ because C ++ has polymorphism, but C ++ is one of C.
Superset, the following technologies can also be used in C ++ programs. Limited to my own level, if
Please correct me for any improper information.

(1) write a simple variable parameter C function

Next we will discuss how to write a simple variable parameter C function.
C functions use the following Macros in the program:
Void va_start (va_list arg_ptr, prev_param );

Type va_arg (va_list arg_ptr, type );

Void va_end (va_list arg_ptr );
Va here is the meaning of Variable-argument (Variable Parameter.
These macros are defined in stdarg. H, so programs that use variable parameters should include
Header file. Below we will write a simple variable parameter function. The function should have at least one integer.
Parameter. The second parameter is also an integer and is optional. The function only prints the values of these two parameters.
Void simple_va_fun (int I ,...)
{
Va_list arg_ptr;
Int J = 0;

Va_start (arg_ptr, I );
J = va_arg (arg_ptr, INT );
Va_end (arg_ptr );
Printf ("% d/N", I, j );
Return;
}
We can declare our function in our header file as follows:
Extern void simple_va_fun (int I ,...);
We can call it in the program as follows:
Simple_va_fun (100 );
Simple_va_fun (100,200 );
From the implementation of this function, we can see that the following steps should be taken to use variable parameters:
1) first define a va_list variable in the function. Here is arg_ptr. This variable
Volume is a pointer to a parameter.
2) then use the va_start macro to initialize the variable arg_ptr. The second parameter of this macro is
The previous parameter of a variable parameter is a fixed parameter.
3) then return the variable parameter with va_arg and assign the value to the second integer J. va_arg.
The parameter is the type of the parameter you want to return. Here it is the int type.
4) use the va_end macro to end variable parameter acquisition. Then you can make
The second parameter is used. If the function has multiple variable parameters, call va_arg to obtain
Take parameters.
If we call the following three methods, they are all legal, but the results are different:
(1) simple_va_fun (100 );
Result: 100-123456789 (changed value)
(2) simple_va_fun (100,200 );
Result: 100 200
(3) simple_va_fun (100,200,300 );
Result: 100 200
We can see that there is an error in the first call, the second call is correct, and the third call despite the result
Correct, but there is a conflict with the initial design of our function. The following section describes the results.
And how variable parameters are processed in the compiler.

(2) Processing of variable parameters in the Compiler

We know that va_start, va_arg, and va_end are defined as Macros in stdarg. h,
Because 1) different hardware platforms 2) Different compilers, the defined macros are also different.
The following is an excerpt from the macro definition of the x86 Platform in stdarg. h in VC ++ ('/' indicates a line break ):

Typedef char * va_list;

# DEFINE _ intsizeof (N )/
(Sizeof (n) + sizeof (INT)-1 )&~ (Sizeof (INT)-1 ))

# Define va_start (AP, V) (AP = (va_list) & V + _ intsizeof (v ))

# Define va_arg (AP, T )/
(* (T *) (AP + = _ intsizeof (t)-_ intsizeof (t )))

# Define va_end (AP) (AP = (va_list) 0)

Definition _ intsizeof (n) is mainly used for some systems that require memory alignment. c letters
The number is pushed to the stack from the right to the left. Figure (1) shows the distribution position of function parameters in the stack. I
We can see that va_list is defined as char *, and some platforms or operating systems are defined as void *.
Look at the definition of va_start, which is defined as & V + _ intsizeof (V), while & V is a fixed parameter in the stack
So after we run va_start (AP, V), the AP points to the first variable parameter in the heap
Stack address ,:

High address | ----------------------------- |
| Function return address |
| ----------------------------- |
| ...... |
| ----------------------------- |
| Nth parameter (the first variable parameter) |
| ----------------------------- | <-- After va_start, the AP points
| N-1 parameter (the last fixed parameter) |
Low address | ----------------------------- | <-- & V
Figure (1)

Then, we use va_arg () to obtain the variable parameter value of type T. The above example is int type.
Let's take a look at the return value of the int type for va_arg:
J = (* (int *) (AP + = _ intsizeof (INT)-_ intsizeof (INT )));
First, ap + = sizeof (INT), pointing to the address of the next parameter. Then, return
AP-sizeof (INT) int * pointer, which is the address of the first variable parameter in the stack
(Figure 2). Then, use * to get the content of this address (parameter value) and assign it to J.

High address | ----------------------------- |
| Function return address |
| ----------------------------- |
| ...... |
| ----------------------------- | <-- Va_arg
| Nth parameter (the first variable parameter) |
| ----------------------------- | <-- After va_start, the AP points
| N-1 parameter (the last fixed parameter) |
Low address | ----------------------------- | <-- & V
Figure (2)

The last thing we want to talk about is the va_end macro. The X86 platform is defined as AP = (char *) 0, so that the AP is no longer
Point to the stack, but like null. Some are directly defined as (void *) 0), so the compiler does not
Code is generated for va_end. For example, GCC is defined in this way on the x86 Platform of Linux.
You should pay attention to one problem here: Because the address of the parameter is used for the va_start macro
The parameter cannot be declared as a register variable or as a function or array type.
This is the description of va_start, va_arg, and va_end.
Different operating systems and hardware platforms have different definitions, but their principles are similar.

(3) Notes for variable parameters in programming

Because va_start, va_arg, and va_end are defined as macros, it seems stupid,
The type and number of variable parameters are completely controlled by the program code in this function, and cannot be intelligent.
To identify the number and type of different parameters.
Someone may ask: Isn't Intelligent Recognition parameters implemented in printf? That's because the function
Printf analyzes the parameter type from a fixed format string, and then calls va_arg
To obtain variable parameters. That is to say, if you want to intelligently identify variable parameters
Through making judgments in your own program.
Another problem is that the compiler does not strictly check the prototype of the Variable Parameter Function.
If simple_va_fun () is changed:
Void simple_va_fun (int I ,...)
{
Va_list arg_ptr;
Char * s = NULL;

Va_start (arg_ptr, I );
S = va_arg (arg_ptr, char *);
Va_end (arg_ptr );
Printf ("% d % s/n", I, S );
Return;
}
The variable parameter is char * type. When we forget to use two parameters to call this function
Core Dump (UNIX) or an invalid page error (Windows platform ).
Errors, but they are hard to find, making it difficult for us to write high-quality programs.
The following describes the compatibility of VA macros.
System v unix defines va_start as a macro with only one parameter:
Va_start (va_list arg_ptr );
Ansi c is defined:
Va_start (va_list arg_ptr, prev_param );
If we want to use the definition of System V, we should use
Macros and ansi c macros are incompatible with system v macros. We generally use ansi c, so
It is enough to use the definition of ansi c to facilitate program transplantation.

Summary:
The function principle of variable parameters is actually very simple, while the VA series are defined by Macro.
It is related to the stack. When we write a Variable Function C function, it has both advantages and disadvantages, so we do not have
Variable parameters are not required. In C ++
To implement the Variable Parameter Function, try to avoid using the C language.

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.