https://godbolt.org/z/YK5PPvz7d

#include <stdio.h>

struct file_format_a_header 
{
    int i;
};

struct file_format_b_header 
{
    int i;
};

int main()
{
    int type = 1;
    size_t len = 0;

    if (1 == type)
    {
        len = sizeof(struct file_format_a_header ); // sizeof file_format_a_header and file_format_b_header  is SAME but they are different structures
    }
    else
    {
        len = sizeof(struct file_format_b_header );
    }

    printf("len = %zu\n", len);
    return 0;
}


<source>: In function 'main':
<source>:18:8: error: this condition has identical branches [-Werror=duplicated-branches]
   18 |     if (1 == type)
      |        ^
cc1: all warnings being treated as errors
ASM generation compiler returned: 1
<source>: In function 'main':
<source>:18:8: error: this condition has identical branches [-Werror=duplicated-branches]
   18 |     if (1 == type)
      |        ^
cc1: all warnings being treated as errors
Execution build compiler returned: 1

GCC切换:

-std=gnu11
-Wall
-Werror
-Wextra
-Wduplicated-branches

问题&gt;有没有办法解决GCC的这个警告?

推荐答案

GCC可能会在这里生成警告,因为sizeof运算符的结果是编译时间常量(除非其操作数是可变长度数组).

因此,它实际上看到了这一点:

    if (1 == type)
    {
        len = 4;
    }
    else
    {
        len = 4;
    }

即使两个 struct 具有不同的成员名称、不同的成员类型或不同数量的成员,只要大小相同,也会发生这种情况.

您可以通过添加pragma来解决此问题,以在特定范围内忽略此特定警告:

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wduplicated-branches"
    if (1 == type)
    {
        len = sizeof(struct ABC);
    }
    else
    {
        len = sizeof(struct abc);
    }
#pragma GCC diagnostic pop

C++相关问答推荐

无法用C++编译我的单元测试

以下声明和定义之间的区别

GDB输出ARM助记符

将返回的char*设置为S在函数中定义的字符串文字可能会产生什么问题?

S在本文中的价值观到底出了什么问题?

关于scanf()和空格的问题

指向不同类型的指针是否与公共初始序列规则匹配?

如何用C语言为CLI应用程序编写按键检测系统?

如何使用libgpio(d)为Raspberry Pi编译C程序?

如何在双向表中实现线程安全,每个条目仅使用4位,同时避免任何全局锁?

将回调/基于事件的C API转换为非回调API

Fscanf打印除退出C代码为1的程序外的所有内容

被调用方函数内部的C-Struct变量,它是指针还是无关紧要

共享内存未授予父进程权限

struct 中的qsort,但排序后的 struct 很乱

函数的typedef是标准 C 语法吗?它与函数指针的typedef有何不同?

memcmp 是否保证按顺序比较字节?

读取包含指向列表的指针的段寄存器 (%gs)

关于将十六进制常量分配给signed类型变量的说明

在C语言中实现defer关键字