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,855 questions

51,776 answers

573 users

What is the difference between union and struct in C++

2 Answers

0 votes
#include <iostream>
 
struct st {         
    int a;
    char s[20];
    float f;
};
 
union un {      
    int a;
    char s[20];
    float f;
};
 
int main()
{
    struct st s;
    union un u;
     
    std::cout << sizeof(st) << "\n";
    std::cout << sizeof(un);
     
    return 0;
}
    
    
    
/*
run:
    
28
20
    
*/

 



answered Dec 11, 2020 by avibootz
edited Dec 11, 2020 by avibootz
0 votes
#include <iostream>
#include <cstring>

struct st {         
    int a;
    char s[20];
    float f;
};
 
union un {      
    int a;
    char s[20];
    float f;
};
 
int main()
{
    struct st s;
    union un u;
     
    // only one union member can be used at a time
    u.a = 546;
    strcpy(u.s, "C++");
    u.f = 3.14;     
    std::cout << u.a  << "\n";
    std::cout << u.s  << "\n";
    std::cout << u.f  << "\n";

    s.a = 546;
    strcpy(s.s, "C++");
    s.f = 3.14;
    std::cout << s.a  << "\n";
    std::cout << s.s  << "\n";
    std::cout << s.f  << "\n";
     
    return 0;
}
    
    
    
/*
run:
    
1078523331
��H@�
3.14
546
C++
3.14
    
*/

 



answered Dec 11, 2020 by avibootz

Related questions

1 answer 87 views
1 answer 87 views
1 answer 96 views
1 answer 108 views
1 answer 97 views
1 answer 74 views
...