Example program for union in C CPP

Coding in C

#include<stdio.h>

struct s
{
char c;
int i;
float f;
};
union u
{
char c;
int i;
float f;
};
int main()
{
struct s sv;
union u uv;
printf(“Size of sv = %d”,sizeof(sv));
printf(“\nSize of uv = %d”,sizeof(uv));
printf(“\nAddres of members of sv: %u %u %u “,&sv.c,&sv.i,&sv.f);
printf(“\nAddres of members of sv: %u %u %u”,&uv.c,&uv.i,&uv.f);
return 0;
}

Coding in C++

#include<iostream>

using namespace std;
struct s
{
char c;
int i;
float f;
};
union u
{
char c;
int i;
float f;
};
int main()
{
s sv;
u uv;
cout<<“Size of sv = “<<sizeof(sv)<<endl;
cout<<“Size of uv = “<<sizeof(uv)<<endl;
cout<<“Address of members of sv: “<<&sv.c<<” “<<&sv.i<<” “<<&sv.f<<endl;
cout<<“Address of members of uv: “<<&uv.c<<” “<<&uv.i<<” “<<&uv.f<<endl;
return 0;
}

Output

Example program for union in C CPP Output

Published by

admin

I am a computer teacher, programmer and web developer