Skip to content

Commit

Permalink
Add snippet
Browse files Browse the repository at this point in the history
  • Loading branch information
Marcondiro committed Aug 24, 2024
1 parent 8349d95 commit 55cff64
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 8 deletions.
19 changes: 11 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
@@ -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/[email protected]/t/#u
Little experiment to check how integer promotion affects bitfields.

The interest in this came after the discussion at <https://lore.kernel.org/all/[email protected]/t/#u>

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://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://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://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://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/32529080/should-bit-fields-less-than-int-in-size-be-the-subject-of-integral-promotion>

https://stackoverflow.com/questions/46073295/implicit-type-promotion-rules
<https://stackoverflow.com/questions/46073295/implicit-type-promotion-rules>
33 changes: 33 additions & 0 deletions main.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#include <stdio.h>

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
*/

0 comments on commit 55cff64

Please sign in to comment.