Search code examples
cgcccompiler-warningssuppress-warnings

GCC conversion warning when assigning to a bitfield


Is there any way to supress the warning generated by gcc in this code:

int main() {
    struct flagstruct {
        unsigned flag : 1;
    } a,b,c;

    a.flag = b.flag | c.flag;

    return a.flag;
}

The warning is

warning: conversion to 'unsigned char:1' from 'int' may alter its value [-Wconversion]

It looks like the the two flags are extended to int when ored together. What I think is really strange is that casting any of the two flags to unsigned supresses the warning.

a.flag = (unsigned)b.flag | c.flag;

Is this a compiler bug or is it supposed to work this way?


Solution

  • After one year I revised the issue:

    Just tested again with different compiler versions. When I first ran into this bug (now I am quite sure, I am allowed to call it a bug), I already realized the warning existed only in clang < 3.1 and all GCC versions at that time. The warning is still produced by all GCC versions < 5.

    Since there is no other way to silence the error, the only solution is to update to GCC > 5 or add the unsigned cast a.flag = (unsigned)b.flag | c.flag;.