c - C 中标准类型的 typedef 的推荐方法?

标签 c typedef

对于 C 中的标准类型,推荐的 typedef 方法是什么?

例如,在我的项目开始时,我创建了 typedef 以使用尽可能小的类型来实现它们的目的。主要目的是在使用的数值范围对于类型而言变得太大的情况下允许轻松修改类型,而无需对整个项目进行全局搜索+替换。但六个月后我并不满意,认为一定有更好的方法。

这些是我定义的类型:

/*  type to be used for storing map data within
    n*n array                                   */
typedef unsigned char map_t;

/*  type to be used for storing coordinates in map.
    min 0,max 32 (MAP_W,MAP_H defaults). note: no
    longer requires signed.                     */
typedef unsigned char xy_t;

/*  type to be used for counters, ie moves_remaining
    has max 2000                                */
typedef signed int ctr_t;

/*  type to be used for storing the level number,
    requires signed.                            */
typedef signed short lvl_t;

/*  type to be used for storing contact types,
    see actions.h CONTACT                       */
typedef signed short ct_t;

/*  small unsigned type, miscellaneous          */
typedef unsigned char su_t;

/*  small signed type, miscellaneous            */
typedef signed char ss_t;

struct xy
{
    xy_t x;
    xy_t y;
};

struct scrxy
{
    int x;
    int y;
};

struct xy_offset
{
    ss_t x;
    ss_t y;
};

一些代码,而不是使用签名类型并检查 n < 0 && n > max_val使用无符号类型并且只检查 n > max_val其中 max_val小于 T_MAX尽管我后来发现这种行为实际上是未定义的。

我应该删除所有这些吗 typedef s 并使用 stdint.h 中定义的标准类型而不是贯穿我的代码(大小现在已经相当稳定)?

最佳答案

我个人会根据 stdint.h 类型定义所有这些 max_t 等类型:

typedef uint8_t map_t;

除了这两种“杂项”类型之外,我自己也会使用类似的方法 - 启用有关整数转换和比较的所有编译器警告和错误。

如果你想要更精确的类型定义并使用 Ada,我想你需要切换编程语言 :)

关于c - C 中标准类型的 typedef 的推荐方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1620650/

相关文章:

c - 打印文件内容

c++ - 类模板中的 Typedef 指针

c - void typedef 在 C 中如何工作

python - 使用 ctypes 映射基本 typedef 别名?

c++ - Typedef C++ 中的枚举值

c - 关于typedef中单实例数组的一些问题

c - 如何检测字符缓冲区编码?

c - 3d 数组作为函数参数

c++ - 使用 Makefile 的交叉编译使用了错误的包含

c - 在文件中添加日期 - C