C language variable parameters

C language variable parameters

  The C language allows the definition of a function with a variable number of parameters, which is called a variadic function. Such functions require a fixed number of mandatory arguments, followed by a variable number of optional arguments.

1. Deformable parameter correlation function

#include <stdarg.h>
void va_start(va_list ap, last);
type va_arg(va_list ap, type);
void va_end(va_list ap);
void va_copy(va_list dest, va_list src);

  va_start completes the initialization of the ap pointer for subsequent use by va_arg and va_end , this function must be called first. The parameter last is the name of the last parameter before the variable parameter list;
  va_arg realizes the acquisition of the type and value of the next parameter. The parameter ap is the parameter list initialized by va_start. Each call to va_arg() modifies ap in order to get the next argument. The parameter type type is a specified data type.
  va_end points ap to NULL.
  va_copy copies the parameter list src to dest, this function is only defined in c99.

2. Deformable parameters imitate the printf function

#include <stdio.h>
#include <stdarg.h>
void my_printf(const char *fmt,...);
int main()
{
    
    
	my_printf("%s\n","123456");
	my_printf("%d %%\n",55);
	my_printf("%f\n",789.56);
	my_printf("%c\n",'c');
	my_printf("%ld,%lf\n",1234567890123,45.789625);
}
void my_printf(const char *fmt,...)
{
    
    
	va_list ap;
	va_start(ap,fmt);//ap=fmt
	char c,*s;
	int d;
	float f;
	long l;
	double b;
	while(*fmt)
	{
    
    
		if(*fmt!='%')
		{
    
    
			putchar(*fmt);//输出%前所有字符
		}
		else 
		{
    
    
			fmt++;//跳过%
			switch(*fmt)
			{
    
    
				case 'c'://字符
					c=(char )va_arg(ap,int);//字符存储时按int空间处理
					fprintf(stdout,"%c",c);
					break;
				case 'd'://整数
					d=va_arg(ap,int);
					fprintf(stdout,"%d",d);
					break;
				case 'f'://浮点数
					f=(float)va_arg(ap,double);//浮点数据处理时按double处理
					fprintf(stdout,"%f",f);
					break;
				case '%'://%%
					putchar(*fmt);
					break;
				case 's'://字符串
					s=va_arg(ap,char *);
					fprintf(stdout,"%s",s);
					break;
				case 'l':
					fmt++;
					if(*fmt=='d')//长整形%ld
					{
    
    
						l=va_arg(ap,long);
						fprintf(stdout,"%ld",l);
					}
					else if(*fmt=='f')//双精度浮点型%lf
					{
    
    
						b=va_arg(ap,double);
						fprintf(stdout,"%lf",b);
					}
					break;
			}
		}
		fmt++;
	}
	va_end(ap);//ap=NULL
}

  running result:

[wbyq@wbyq 0414work]$ gcc main.c 
[wbyq@wbyq 0414work]$ ./a.out 
123456
55 %
789.559998
c
1234567890123,45.789625

Guess you like

Origin blog.csdn.net/weixin_44453694/article/details/124271934