[go: up one dir, main page]

0% found this document useful (0 votes)
6 views2 pages

Program 8

The C program demonstrates the difference between structures and unions. Structures allow multiple members to be stored independently, while unions share the same memory space for their members, meaning only one member can hold a value at any time. The program also prints the sizes of both the structure and the union.

Uploaded by

shashikalahc451
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views2 pages

Program 8

The C program demonstrates the difference between structures and unions. Structures allow multiple members to be stored independently, while unions share the same memory space for their members, meaning only one member can hold a value at any time. The program also prints the sizes of both the structure and the union.

Uploaded by

shashikalahc451
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

8. Write a C program to differentiate between structures and union.

#include <stdio.h>
// Definition of Structure
struct Structure {
int a;
float b;
char c;
};
// Definition of Union
union Union {
int a;
float b;
char c;
};
int main() {
// Declaring structure and union variables
struct Structure s;
union Union u;
// Assigning values to structure members
s.a = 10;
s.b = 20.5;
s.c = 'X';

// Assigning values to union members


u.a = 10; // Assigning a value to the first member (int)
// u.b = 20.5; // If you uncomment this, it will overwrite 'u.a' due to shared memory space.
//u.c = 'Y'; // Assigning a value to the third member (char)

// Printing values of the structure


printf("Structure: \n");
printf("s.a = %d, s.b = %.2f, s.c = %c\n", s.a, s.b, s.c);

// Printing values of the union


printf("Union: \n");
printf("u.a = %d, u.b = %.2f, u.c = %c\n", u.a, u.b, u.c);

// Showing the size of structure and union


printf("\nSize of Structure: %lu bytes\n", sizeof(s));
printf("Size of Union: %lu bytes\n", sizeof(u));

return 0;
}

OUTPUT:

You might also like