【发布时间】:2017-05-10 11:15:32
【问题描述】:
受到question 的启发,我有:
#include<stdio.h>
struct st
{
int a:1;
int b:2;
};
int main()
{
struct st obj={1, 2};
printf("a = %d\nb = %d\n",obj.a,obj.b);
}
我得到:
Georgioss-MacBook-Pro:~ gsamaras$ gcc -Wall main.c
main.c:10:26: warning: implicit truncation from 'int' to bitfield changes value
from 2 to -2 [-Wbitfield-constant-conversion]
struct st obj={1, 2};
^
1 warning generated.
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out
a = -1
b = -2
我想我理解为什么两个位域都不能保持它们的值(根据这个answer),但我不明白为什么编译器只警告2,而不是1!有什么想法吗?
我在我的 Mac 上使用:
Georgioss-MacBook-Pro:~ gsamaras$ gcc -v
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 8.1.0 (clang-802.0.38)
Target: x86_64-apple-darwin16.3.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
在使用 gcc 版本 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5) 的旧 Linux 系统中,我没有收到相关警告。
在使用 gcc 版本 4.9.2 (Debian 4.9.2-10) 的 Debian 安装中,我没有收到相关警告!
【问题讨论】:
-
fyi g++ 5.1.0 按预期产生 2 个警告。 2 *
warning: overflow in implicit constant conversion [-Woverflow]
标签: c struct compilation warnings bit-fields