Unions :

What is Union ?

Similar to a structure, a union also consists of data members but only one data is active at a time.

Syntax :

  1. union student
  2. {
  3. int roll_no;
  4. char sname[30];
  5. };

Example :

  1. /* Description: union program to store student data */
  2. #include<stdio.h>
  3. union student{
  4. char sname[20];
  5. }
  6. main()
  7. {
  8. union student std;
  9. puts("Enter student name : ");
  10. gets(std.sname);
  11. puts("\n------ DATA STORE COMPLETED ------\n");
  12. printf("Student Name is : %s.",std.sname);
  13. puts("\n------ DATA STORE COMPLETED ------");
  14. printf("Student Name is : %s.",std.sname);
  15. getch();
  16. }

Output :

c language - union program to store student data

sizeof() of a union :

sizeof() a union is equal to the number of bytes occupied in RAM by the largest data member in the union.

Example :

  1. /* Description: find size of union */
  2. #include<stdio.h>
  3. union student{
  4. char username[5];
  5. char sname[20];
  6. }
  7. main()
  8. {
  9. printf("\n size of this union - %d.",sizeof(union student));
  10. getch();
  11. }

The size of this union equal 20bytes because the largest data member sname occupies 20bytes in RAM.

Output :

c language - union program to store student data

enum :

enum represents the enumeration data type which is used to instruct the compiler to associate with the specific list of values for a variables.

Example :

  1. /* Description: write a simple program use enum */
  2. #include<stdio.h>
  3. enum week{sunday, monday, tuesday, wednesday, thursday, friday, saturday};
  4. main()
  5. {
  6. enum week today;
  7. today = monday;
  8. printf("\n Day %d.",today+1);
  9. getch();
  10. }

Output :

c language - write a simple program use enum

Next Update

Loading...

We have two YouTube channels their name is CodeX or NightHawk. CodeX is for programming related videos and NightHawk is for online game streaming so please supporting us and Subscribe to our channels