0
#include <stdio.h> 
int main(void)
{
    union Acnt
    {
        int Acno,Bal;
        char name[10];
        float EMI;
    };

    printf("%d", sizeof(union Acnt));
    return 0;
}

The largest member size in this union is 10. But the output is 12. Please explain why.

Jens
  • 69,818
  • 15
  • 125
  • 179
  • 3
    `sizeof` returns a value of type `size_t`. To print it either use `"%zu"` (if you have a C99 implementation) or cast the value (to `unsigned long int` and use `"%lu"`). – pmg May 02 '14 at 10:18
  • 5
    a multiple of 8 and 4 for alignment of data. – BLUEPIXY May 02 '14 at 10:19
  • can you please elaborate the explanation BLUEPIXY – user3479901 May 02 '14 at 10:23
  • The compiler probably expands it to the nearest multiple of 4. You should be able to revoke this behavior with an appropriate `#pragma` I suppose. The reason for the expansion is so that if you have an array of `Acnt` elements, each one of them will be aligned to 4 bytes, and the `int` and `float` fields of each element will also be aligned to 4 bytes. – barak manos May 02 '14 at 10:26
  • This is not a duplicate question as far as I can see.. – Martin G May 02 '14 at 10:36
  • @scy7he Dunno why you can't see that it's obviously blatantly definitely a duplicate. Ones a struct and the other's a union but the reasons are the same. There's probably a better dup around, but the Q is already closed. – Jim Balter May 02 '14 at 10:44

1 Answers1

3

The total size of a union will be the smallest integer that is greater than (or equal to) the required size and is a multiple of the largest type in the union . In your case the union will be padded to the smallest multiple of size of float/int >= 10. You can prevent padding via the pack pragma:

#include <stdio.h>
int main(int argc, char *argv[]) {
#pragma pack(push, 1)
    union Acnt
    {   
        int Acno,Bal;
        char name[10];
        float EMI;
    };  
#pragma pack(pop)

        printf("%d",sizeof(union Acnt));
    return 0;
}
perreal
  • 94,503
  • 21
  • 155
  • 181