gpt4 book ai didi

c - 常量数组的全局变量的替代品?

转载 作者:行者123 更新时间:2023-11-30 14:52:03 27 4
gpt4 key购买 nike

我在学校有一个重新创建 printf 的项目。

我不想一直在代码中检查字符的格式说明符,因为我发现它很困惑且丑陋。

就目前而言,我已经找到了一种方法,通过创建一些全局常量数组并使用它们进行检查。但我不喜欢在代码中包含这么多全局变量。

这是全局变量可以使用的情况之一吗?或者我应该使用其他方法来获得我想要的东西?

这是我的开始方式:

全局常量数组

const char  g_sp_integer[] = {
'd', //signed decimal int
'i', //signed decimal int
'o', //unsigned octal
'u', //unsigned decimal int
'x', //unsigned hex int
'X', //unsigned hex int (uppercase)
'\0'
};

我的标题

#ifndef  FT_PRINTF_H
# define FT_PRINTF_H

# include <stdarg.h>
# include <stdint.h>
# include <stdlib.h>

# include "libft.h"

# define SUCCESS (int32_t)0
# define FAILURE (int32_t)-1

/*
** Those extern definitions are used to check the specifier flags
*/

extern const char *g_sp_integer;

int ft_printf(const char *format, ...);

#endif

还有我的 printf 函数

#include "ft_printf.h"

static int32_t is_sp_integer(char c)
{
uint32_t i;

while (g_sp_integer[i] != '\0')
{
if (g_sp_integer[i] == c)
return (i);
++i;
}
return (FAILURE);
}

int ft_printf(const char *format, ...)
{
va_list ap;
char *tmp;
int32_t sp_type;

tmp = format;
va_start(ap, format);
while (tmp != '\0')
{
if (tmp != '%')
{
ft_putchar(tmp);
continue;
}
if ((sp_type = is_sp_integer(++tmp)) != FAILURE)
; //parse_flag(sp_type);
//continue checking the type of the specifier
}
va_end(ap);
return (SUCCESS);
}

我想避免什么:

这些只是最基本的原型(prototype),但我想知道是否有适当的方法可以使我的函数变得如此干净。在我看来,这意味着如果可能的话,我想避免进行这样的检查:

if (c == 'd' || c == 'i')
//manage the integer flag
else if (c == 'o')
//manage the octal flag, etc.

如果不可能,并且最好的方法是我想避免的方法,请告诉我!

感谢大家的耐心等待,因为有时很难找到好的做法!

编辑:

我使用的解决方案:

虽然第一个解决方案对我在这种情况下应该做什么(在该文件中使用静态变量)有全局答案,但我已经结束了第二个答案中建议的操作,因为它符合我的需要,并避免使用静态或全局变量。

这是我的函数的代码:

static int32_t is_sp_integer(char c) {
const char *sp_integer;
const char *sp_ptr;

sp_integer = "dDioOuUxX";
sp_ptr = sp_integer;
while (*sp_ptr != '\0')
{
if (*sp_ptr == c)
return (sp_ptr - sp_integer);
++sp_ptr;
}
return (FAILURE);
}

谢谢大家!

最佳答案

g_sp_integer 仅在 is_sp_integer 函数内部使用,因此在那里定义它:

static int32_t  is_sp_integer(char c)
{
const char g_sp_integer[] = {
'd', //signed decimal int
'i', //signed decimal int
'o', //unsigned octal
'u', //unsigned decimal int
'x', //unsigned hex int
'X', //unsigned hex int (uppercase)
'\0'
};

uint32_t i;

while (g_sp_integer[i] != '\0')
{
if (g_sp_integer[i] == c)
return (i);
++i;
}
return (FAILURE);
}

关于c - 常量数组的全局变量的替代品?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47778746/

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