When I run sizeof(r) on my Mac. It says sizeof(r) = 1. My understanding is that the size of a union is the size of its largest element. In this case shouldn’t the largest element be the struct s?
union
{
struct
{
char i:1;
char j:2;
char m:3;
}s;
char ch;
}r;
Your union composes of two parts, a struct, and a character. The size of the union, since it shares the memory, is the size of the largest element, plus the size of any padding it sticks on (which in your case is 0 bytes).
First, let’s see the size ideone reports for each:
http://ideone.com/LAhop
Okay, both are 1. Therefore, the union’s size must be 1 as well.
The struct is composed of bitfields. One is 1 bit, one is 2, and one is 3. This gives a total of 6 out of the 8 bits in one byte. Since it has to be at least one byte anyway (bitfields aren’t really sized in bits), the size is 1.
As for char, here’s what the C++11 standard says in § 3.9.1/1 [basic.fundamental]:
For pretty much every platform, this is one byte.This is one byte.