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 119 views
1 answer 112 views
1 answer 130 views
1 answer 147 views
1 answer 130 views
...