1

enter image description here

try below code at - https://onlinegdb.com/H1Sf_PAiI

#include<iostream>
using namespace std;

struct Str
{
    char c;
    int ch1:56;
    double d;
    int s;
    int ch:32;  
}st;
int main()
{
    cout<<sizeof st<<endl;

    return 0;
}

output

main.cpp:7:10: warning: width of ‘Str::ch1’ exceeds its type                                                                          
32

Then I reduced ch1 bit field to 32 bits. It worked..!

try below code at - https://onlinegdb.com/BkD4YP0oI

#include<iostream>
using namespace std;

struct Str
{
    char c;
    int ch1:32;
    double d;
    int s;
    int ch:32;  
}st;
int main()
{
    cout<<sizeof st<<endl;

    return 0;
}

output

24

Rule 1 and 2 in the above image are incorrect?

Sathvik
  • 565
  • 1
  • 7
  • 17
  • 4
    Rules 1 and 2 are incorrect. The address will be a multiple of the alignment requirement of the type. The size of a struct (or union) will be a multiple of the maximum alignment requirement of its members. – Ian Abbott May 29 '20 at 11:09
  • About the warning: `int` is (presumably) 32 bit on your platform, so `:52` is incorrect. You should use a larger data type, such as `long long` – mrksngl May 29 '20 at 11:12
  • @mrksngl Yes, although support for data types other than `_Bool`, `signed int` and `unsigned int` is implementation-defined for bit-fields. – Ian Abbott May 29 '20 at 11:22
  • @IanAbbott can you please elaborate your answer. It looks like rule 1 and 2 are same as your explanation. – Sathvik May 29 '20 at 11:39
  • 2
    @Sathvik there is a difference: the alignment requirement of a type might not equal its size – harold May 29 '20 at 12:01
  • 2
    @Sathvik For example, on 32-bit x86, an 8-byte (64-bit) `long long int` might not be placed on an 8-byte boundary. It could be placed on any 4-byte boundary. On such a platform, `_Alignof(long long int)` would be 4 rather than 8, and a `struct` containing a `char` and a `long long int` would have size 12 rather than 16. – Ian Abbott May 29 '20 at 12:19
  • @IanAbbott got it – Sathvik May 29 '20 at 12:29
  • ```structure Str{char c; int ch2:24; int ch1:32; double d; int s; int ch:32;};``` It occupies full structure storage – Sathvik May 29 '20 at 13:30

0 Answers0