gpt4 book ai didi

c - C编程的良好礼仪

转载 作者:太空狗 更新时间:2023-10-29 15:08:50 25 4
gpt4 key购买 nike

<分区>

我目前正在编写自己的 printf 实现,代码如下:

int my_printf(const char *format, ...)
{
//Declare variable ou prog fonctionnel????
va_list args;
int numberValue;
unsigned int unsignedNumberValue;
double doubleValue;
char* stringValue;
char charValue;
va_start(args, format);
for(int i = 0; format[i]; i++){
//This case is the most called case, so we test it first to get the
//best perfs
if(format[i] != '%'){
my_put_char(format[i]);
}else{
if(format[i+1] == 'd' || format[i+1] == 'i'){
numberValue = va_arg(args, int);
my_put_nbr(numberValue);
}else if(format[i+1] == 'u'){
unsignedNumberValue = va_arg(args, unsigned int);
my_put_nbr_unsigned(unsignedNumberValue);
}else if(format[i+1] == 'o'){
numberValue = va_arg(args, int);
my_put_nbr_base(numberValue, 2);
}else if(format[i+1] == 'c'){
//char parameters are passed as integer as va_args
charValue = va_arg(args, int);
my_put_char(charValue);
}else if(format[i+1] == 's'){
stringValue = va_arg(args, char*);
my_puts(stringValue);
}else if(format[i+1] == 'f'){
doubleValue = va_arg(args, double);
my_put_double(doubleValue);
}else if(format[i+1] == '%'){
my_put_char('%');
}else{
//error option not handled
char* error = my_strcat("\nThe option you provided is not a valid option: %", &format[i + 1], 1);
write(2, error, sizeof(char) * my_strlen(error));
}
i++;
}
}
va_end(args);
return 0;
}

我想知道关于我的代码的两件事:

  • 我想知道我是否应该编写“函数方式”编程,例如不使用变量并将直接调用的va_args 放在my_put 中功能。但是这样做,它将分配和释放每个循环,而不是一个可能不会被使用的声明(分配)和一个在函数结束时释放的。在大过程中,我认为最好将返回值存储到一个变量中,然后调用“函数方式”函数。 (例如对于非常大的文本的 strlen)
  • 我还想知道如何在我的代码中处理可以用不同类型调用的函数,例如 my_put_nbr,我不能重载它们吗?看来它必须有不同的名称。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com