c - 是否有可以指示任何类型更改的 GCC 警告?
问题描述
我的代码中有以下 typedef:
#define ROLLOVERDETECTION_OFF 0
#define ROLLOVERDETECTION_ON 1
typedef uint8_t rolloverdetection;
#define ROLLOVERDETECTED_NO 0
#define ROLLOVERDETECTED_YES 1
#define ROLLOVERDETECTED_UNKNOWN 255
typedef uint8_t rolloverdetected;
这两种类型虽然具有相同的底层类型,但它们不携带相同的信息。
实际上,如果代码中的任何人执行以下操作,我想收到警告:
rolloverdetection detection = ROLLOVERDETECTION_OFF;
// detection is set somewhere else in another function
void get_rolloverdetected(rolloverdetected *outvar)
{
*outvar = detection; // this actually would return the setting of the detection rather than the detection itself
}
我在 gcc 中找不到任何这样的警告选项,我遇到过-Wconversion
,但只有在有可能丢失信息的情况下才会发出警告,而我的示例中并非如此。
有谁知道我能做些什么吗?显然,应该可以在真正需要更改类型时进行强制转换。
解决方案
简短的回答是否定的,你不能这样做。typedef
声明一个别名,而不是一个新类型,所以任何遵守标准的编译器都不能拥有你现在想要的特性。
但是,您可以通过引入新类型、使用枚举或结构来实现它。
如果您在 C 中,您将能够轻松地从一个枚举转换到另一个枚举。
因为结构的第一个元素的地址也是结构的地址,所以您可以将它从 int8 或另一个结构转换为 int8 或另一个结构,方法是转换结构地址,然后用它的新类型取消引用指针。( *((dest_type *)&value)
)
推荐阅读
- html - 如何将所有标题元素设置为字体系列,但使用 SCSS 单独更改每个字体大小?
- python-3.x - 如何将我的 fastapi 请求标头操作为可变的
- reactjs - ReactJS 在我的嵌套迭代器中没有显示
- python - 如何使用正则表达式过滤删除某些数据框列,但保留包含某些字符的其他列?
- javascript - 基于真/假值的文本颜色
- java - JPA + Hibernate:如何将数组绑定与 CriteriaBuilder 一起使用,即使最终查询类似于“... in (?)”,而不是“... in (?, ?, ?)”?
- node.js - Nodemon不使用express在docker中更改时重新加载文件
- tableau-api - 查找的替代方案
- r - 这是如何错误的参数数量?
- list - 我如何将列表划分为总和到给定数字(不重复)的子集?