Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fix "this condition has identical branches" in GCC?

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 switches:

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

Question> Is there a way that I can fix this GCC warning?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

gcc is likely generating a warning here because the result of the sizeof operator is a compile time constant (unless its operand is a variable length array).

So effectively it sees this:

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

This is happening even if the two structs in question have differently named members, differing member types, or a differing number of members, as long as the sizes are the same.

You can work around this by adding pragma to ignore this specific warning in a particular scope:

#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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading