首页 > 解决方案 > 是否有可以指示任何类型更改的 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,但只有在有可能丢失信息的情况下才会发出警告,而我的示例中并非如此。

有谁知道我能做些什么吗?显然,应该可以在真正需要更改类型时进行强制转换。

标签: cgcc

解决方案


简短的回答是否定的,你不能这样做。typedef声明一个别名,而不是一个新类型,所以任何遵守标准的编译器都不能拥有你现在想要的特性。

但是,您可以通过引入新类型、使用枚举或结构来实现它。

如果您在 C 中,您将能够轻松地从一个枚举转换到另一个枚举。

因为结构的第一个元素的地址也是结构的地址,所以您可以将它从 int8 或另一个结构转换为 int8 或另一个结构,方法是转换结构地址,然后用它的新类型取消引用指针。( *((dest_type *)&value))


推荐阅读