Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 answers

573 users

How to define and use union in C

1 Answer

0 votes
#include <stdio.h>
#include <stdint.h>

union U
{
    uint32_t u32;
    uint16_t u16[3];
    uint8_t  u8;
} u = {10000002}; 

int main(void)
{

    printf("Union size: %lu\n", sizeof u);
    printf("u32: %llu\n", u.u32);
    printf("u16[1]: %u\n", u.u16[1]);
    printf("u8: %u\n\n", u.u8);
    
    u.u16[1] = 200; 
    printf("Union size: %lu\n", sizeof u);
    printf("u32: %llu\n", u.u32);
    printf("u16[1]: %u\n", u.u16[1]);
    printf("u8: %u\n\n", u.u8);
    
    u.u8 = 21; 
    printf("Union size: %lu\n", sizeof u);
    printf("u32: %llu\n", u.u32);
    printf("u16[1]: %u\n", u.u16[1]);
    printf("u8: %u\n", u.u8);

        
    return 0;
}

/*
run:
 
Union size: 8
u32: 10000002
u16[1]: 152
u8: 130

Union size: 8
u32: 13145730
u16[1]: 200
u8: 130

Union size: 8
u32: 13145621
u16[1]: 200
u8: 21

*/

 



answered Aug 29, 2016 by avibootz

Related questions

1 answer 134 views
2 answers 272 views
1 answer 175 views
1 answer 117 views
2 answers 133 views
...