分配给位域时的GCC转换警告 [英] GCC conversion warning when assigning to a bitfield
问题描述
有什么方法可以抑制这段代码中gcc生成的警告:
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;
}
警告是
warning: conversion to 'unsigned char:1' from 'int' may alter its value [-Wconversion]
看起来当将两个标志一起使用时,这两个标志被扩展为int. 我认为真正奇怪的是,将两个标志中的任何一个都强制转换为未签名的警告.
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?
推荐答案
一年后,我修改了该问题:
After one year I revised the issue:
仅使用不同的编译器版本进行再次测试.当我第一次遇到此错误(不完全确定,我可以称它为错误)时,它已经意识到警告仅存在于clang<中. 3.1和当时的所有GCC版本.该警告仍由所有GCC版本< 5.
Just tested again with different compiler versions. When I first run into this bug (no I am quite sure, I am allowed to call it a bug), it 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.
由于没有其他方法可以使错误静音,因此唯一的解决方案是将其更新为GCC> 5或添加未签名的强制转换a.flag = (unsigned)b.flag | c.flag;
.
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;
.
这篇关于分配给位域时的GCC转换警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!