当前位置:网站首页>Review of C language (variable parameters)
Review of C language (variable parameters)
2022-07-28 07:12:00 【The most beautiful wish must be the craziest】
Variable parameters
C Language allows you to define functions with a variable number of parameters , This is called a variable parameter function . This function requires a fixed number of mandatory parameters , Followed by a variable number of optional parameters .
Common variable parameter functions
int printf(const char* format,…)
int scanf(const char *format,…)
Fixed parameter format , Optional parameters are “...” Most parameter occupier
Any function with variable parameters can be divided into two parts : Fixed and optional parameters . There must be at least one fixed parameter , Its declaration is the same as that of ordinary function parameters ; The number of optional parameters is uncertain (0 One or more ), The statement is made with "…" Express . Fixed parameters and optional parameters together constitute the parameter list of variable parameter functions .
Variable parameter get object
// function add() Calculate the sum of optional parameters
// Parameters : The first mandatory parameter specifies the number of optional parameters , The optional parameter is double type
// Return value : And the value ,double type
double add( int n, ... )
{
int i = 0;
double sum = 0.0;
va_list argptr;
va_start( argptr, n ); // initialization argptr
for ( i = 0; i < n; ++i ) // For each optional parameter , The read type is double Parameters of ,
sum += va_arg( argptr, double ); // And then add up to sum in
va_end( argptr );
return sum;
}
In the example above , Yes va_list ,va_start,va_arg,va_end Include header file <stdarg.h>
va_list : It's really just through typedef A pointer type defined , It is used to define a pointer .
va_start: In fact, it is to obtain the address of optional parameters , Then save it in the first parameter . It has two parameters , One parameter is va_list Type of , The address used to store the first optional parameter . The other parameter is the mandatory parameter adjacent to the optional parameter . In fact, in the stack of the program , All parameters of the function are continuously distributed in memory , So you can get the address of optional parameters by forcing the address of parameters , Then save it in the first parameter
va_arg: This macro gets type Variable parameter value of type . This function takes two arguments , The first parameter is the address of the current variable parameter , The second parameter is the type of the current variable parameter . Determine the value of variable parameters by address and type , Then return . After this function is called , The value of the first parameter will change , It will point to the next parameter in the parameter list .
va_end: It has to be with va_start In combination with , Use va_start Before exiting the macro function , Must call once va_end macro . It is equivalent to freeing memory .
__VA_ARGS__
Macros with variable parameters , It makes it possible to use variable parameter lists in macro definitions , The minimum number of variable parameters is 1, Otherwise, compilation will fail .
// Usage is as follows , Replace in macro definition ... :
#define my_print2(fmt,...) printf(fmt,__VA_ARGS__)
There's another one ##__VA_ARGS__ , It allows the number of variable parameters to be 0 individual .
#define my_print2(fmt,...) printf(fmt,__VA_ARGS__)
my_print2("i=%d,j=%d\n",i,j) // Print correctly
my_print2("iiiiiii\n") // Compile failed There is only one parameter , The number of variable parameters is 0
// Change it to :
#define my_print2(fmt,...) printf(fmt,##__VA_ARGS__)
my_print2("iiiiiii\n")
vsprintf And vsnprintf
vsprintf And vsnprintf It's almost the same , The difference lies in vsnprintf Limits the maximum conversion length , Can prevent cross-border . General selection vsnprintf.
int vsprintf (char * s, const char * format, va_list arg );
Write the formatted data of the variable parameter list into the character array s in
s: This is a pointer to an array of characters , This array stores the string
format: To format the output string
arg: Variable parameter list
Return value : If it works , Returns the total number of characters written , Otherwise, it returns a negative number
usage :
int vspfunc(char *format, ...)
{
va_list aptr;
int ret;
va_start(aptr, format);
ret = vsprintf(buffer, format, aptr);
va_end(aptr);
return(ret);
}
int main()
{
int i = 5;
float f = 27.0;
char str[50] = "runoob.com";
vspfunc("%d %f %s", i, f, str);
printf("%s\n", buffer);
return(0);
}
int vsnprintf(char *s, size_t n, const char *format, va_list arg)
s: This is a pointer to an array of characters , This array is used to store strings
n: The maximum number of bytes used in the buffer . The length of the generated string is at most n-1, Leave space for additional terminating null characters
format: To format the output string
arg: Variable parameter list
Return value : If it works , Returns the total number of characters written , Does not include terminating null characters , Otherwise, it returns a negative number
usage :
void test(const char * format, ...)
{
char buf[4069];
va_list list;
va_start(list, format);
vsnprintf(buf, 4069, format, list);
va_end(list);
printf("%s\n", buf);
}
边栏推荐
- Standard C language learning summary 8
- Remotely access the local website of services such as neo4j on the ECS
- MOOC Weng Kai C language week 8: pointer and string: 1. Pointer 2. Character type 3. String 4. String calculation
- Joern's code uses -devign
- Joern的代码使用-devign
- Freemaker merges cells, uses if and else tags, and processes null and empty strings
- The.Joernindex database has no content after Joern runs
- YUM仓库的搭建
- Easypoi one to many, merge cells, and adapt the row height according to the content
- Static and floating routes
猜你喜欢

Neo4j运行报错Error occurred during initialization of VM Incompatible minimum and maximum heap sizes spec

easypoi导出表格带echars图表

VLAN的配置

Wangeditor (@4.7.15) - lightweight rich text editor

Neo4j running error occurred during initialization of VM incompatible minimum and maximum heap sizes spec

metasploit渗透ms7_010练习

VNC Timed out waiting for a response from the computer

DNS域名解析

Serial port configuration of raspberry pie

Codesensor: convert the code into AST and then into text vector
随机推荐
SySeVR环境配置:joern-0.3.1、Neo4j-2.1.5、py2neo2.0
Method of decomposing path into directory name and file name
JS string method Encyclopedia
MOOC翁恺C语言第八周:指针与字符串:1.指针2.字符类型3.字符串4.字符串计算
Codesensor: convert the code into AST and then into text vector
Standard C language learning summary 8
Static and floating routes
Canvas drawing 2
MOOC Weng Kai C language week 6: arrays and functions: 1. Arrays 2. Definition and use of functions 3. Parameters and variables of functions 4. Two dimensional arrays
MySQL排除节假日,计算日期差
Esxi community nvme driver update v1.1
easypoi导出表格带echars图表
Starting point Chinese website font anti crawling technology web page can display numbers and letters, and the web page code is garbled or blank
Erudite Valley Learning Records] Super summary, attentive sharing | common APIs
ES6 add -- > object
MOOC Weng Kai C language week 3: judgment and circulation: 2. circulation
Blueberry pie Bluetooth debugging process
MySQL queries all descendant nodes under the parent node. When querying the user list, it is processed by multi-level (company) departments. According to reflection, it recurses the tree structure too
静态和浮动路由
JS data type detection and modification detection