From 55cff6441aa995a15e08f63afbc31337053493d7 Mon Sep 17 00:00:00 2001 From: Marcondiro Date: Sat, 24 Aug 2024 15:05:47 +0200 Subject: [PATCH] Add snippet --- README.md | 19 +++++++++++-------- main.c | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 8 deletions(-) create mode 100644 main.c diff --git a/README.md b/README.md index 67647e5..3238fe4 100644 --- a/README.md +++ b/README.md @@ -1,18 +1,21 @@ # c_bitfields_integer_promotion -Little experiment to check how integer promotion affects bitfields -The interest in this came after the discussion at https://lore.kernel.org/all/6ab8c7fd-c718-49ff-bbbb-9241293127f7@intel.com/t/#u +Little experiment to check how integer promotion affects bitfields. + +The interest in this came after the discussion at + +Turns out that for bitfields bigger than `sizeof(int)` the behavior is compiler dependent. ## A bunch of related links -https://gcc.gnu.org/onlinedocs/gcc/Structures-unions-enumerations-and-bit-fields-implementation.html + -https://stackoverflow.com/questions/2647320/struct-bitfield-max-size-c99-c + -https://www.gnu.org/software/gnu-c-manual/gnu-c-manual.html#Bit-Fields + -https://archive.org/details/the-ansi-c-programming-language-by-brian-w.-kernighan-dennis-m.-ritchie.org/page/132/mode/2up + -https://stackoverflow.com/questions/32529080/should-bit-fields-less-than-int-in-size-be-the-subject-of-integral-promotion + -https://stackoverflow.com/questions/46073295/implicit-type-promotion-rules + diff --git a/main.c b/main.c new file mode 100644 index 0000000..e7912fe --- /dev/null +++ b/main.c @@ -0,0 +1,33 @@ +#include + +struct s1{ + unsigned int a: 20; + unsigned int _: 12; +}; + +struct s2 { + unsigned long long b: 40; + unsigned long long _: 24; +}; + +int main() +{ + struct s1 s1; + struct s2 s2; + + s1.a = 2; + s2.b = 2; + + unsigned int a = s1.a << 19; + unsigned long long b = s2.b << 39; + + printf("0x%x\n", a); //both gcc and clang: 0x100000 + printf("0x%llx\n", b); //gcc: 0x0 clang: 0x10000000000 + + return 0; +} + +/* +Debian clang version 18.1.8 +gcc (Debian 12.2.0-14) 12.2.0 +*/