The Wayback Machine - https://web.archive.org/web/20240917143646/https://www.geeksforgeeks.org/structures-unions-and-enumerations-in-cpp/
Open In App

Structures, Unions and Enumerations in C++

Last Updated : 17 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will discuss structures, unions, and enumerations and their differences.

  • The structure is a user-defined data type that is available in C++.
  • Structures are used to combine different types of data types, just like an array is used to combine the same type of data types.
  • A structure is declared by using the keyword “struct“. When we declare a variable of the structure we need to write the keyword “struct in C language but for C++ the keyword is not mandatory

Syntax:

struct 
{
// Declaration of the struct
}

Below is the C++ program to demonstrate the use of struct:

C++
// C++ program to demonstrate the
// making of structure
#include <bits/stdc++.h>
using namespace std;

// Define structure
struct GFG {
    int G1;
    char G2;
    float G3;
};

// Driver Code
int main()
{
    // Declaring a Structure
    struct GFG Geek;
    Geek.G1 = 85;
    Geek.G2 = 'G';
    Geek.G3 = 989.45;
    cout << "The value is : " << Geek.G1 << endl;
    cout << "The value is : " << Geek.G2 << endl;
    cout << "The value is : " << Geek.G3 << endl;

    return 0;
}

Output
The value is : 85
The value is : G
The value is : 989.45

Explanation: In the above code, values are assigned to the G1, G2, and G3 fields of the structure GFG, and these values are printed at the end.

Structure using typedef: typedef is a keyword that is used to assign a new name to any existing data-type. Below is the C++ program illustrating use of struct using typedef:

C++
// C++ program to demonstrate the use
// of struct using typedef
#include <bits/stdc++.h>
using namespace std;

// Declaration of typedef
typedef struct GeekForGeeks {

    int G1;
    char G2;
    float G3;

} GFG;

// Driver Code
int main()
{
    GFG Geek;
    Geek.G1 = 85;
    Geek.G2 = 'G';
    Geek.G3 = 989.45;

    cout << "The value is : " << Geek.G1 << endl;

    cout << "The value is : " << Geek.G2 << endl;

    cout << "The value is : " << Geek.G3 << endl;

    return 0;
}

Output
The value is : 85
The value is : G
The value is : 989.45

Explanation:

  • In the above code, the keyword “typedef” is used before struct and after the closing bracket of structure, “GFG” is written.
  • Now create structure variables without using the keyword “struct” and the name of the struct.
  • A structure instance has been created named “Geek” by just writing “GFG” before it.

Unions: A union is a type of structure that can be used where the amount of memory used is a key factor. 

  • Similarly to the structure, the union can contain different types of data types.
  • Each time a new variable is initialized from the union it overwrites the previous in C language but in C++ we also don’t need this keyword and uses that memory location.
  • This is most useful when the type of data being passed through functions is unknown, using a union which contains all possible data types can remedy this problem.
  • It is declared by using the keyword “union“.

Below is the C++ program illustrating the implementation of union:

C++
// C++ program to illustrate the use
// of the unions
#include <iostream>
using namespace std;

// Defining a Union
union GFG {
    int Geek1;
    char Geek2;
    float Geek3;
};

// Driver Code
int main()
{
    // Initializing Union
    union GFG G1;

    G1.Geek1 = 34;

    // Printing values
    cout << "The first value at "
         << "the allocated memory : " << G1.Geek1 << endl;

    G1.Geek2 = 'G';

    cout << "The next value stored "
         << "after removing the "
         << "previous value : " << G1.Geek2 << endl;

    G1.Geek3 = 34.34;

    cout << "The Final value value "
         << "at the same allocated "
         << "memory space : " << G1.Geek3 << endl;
    return 0;
}

Output
The first value at the allocated memory : 34
The next value stored after removing the previous value : G
The Final value value at the same allocated memory space : 34.34

Explanation: In the above code, Geek2 variable is assigned an integer (34). But by being of char type, the value is transformed through coercion into its char equivalent (“). This result is correctly displayed in the Output section.

Enums: Enums are user-defined types that consist of named integral constants.

  • It helps to assign constants to a set of names to make the program easier to read, maintain and understand.
  • An Enumeration is declared by using the keyword “enum“.

Below is the C++ program illustrating the use of enum:

C++
// C++ program to illustrate the use
// of the Enums

#include <bits/stdc++.h>
using namespace std;

// Defining  an enum
enum GeeksforGeeks { Geek1, Geek2, Geek3 };

GeeksforGeeks G1 = Geek1;
GeeksforGeeks G2 = Geek2;
GeeksforGeeks G3 = Geek3;

// Driver Code
int main()
{
    cout << "The numerical value "
         << "assigned to Geek1 : " << G1 << endl;

    cout << "The numerical value "
         << "assigned to Geek2 : " << G2 << endl;

    cout << "The numerical value "
         << "assigned to Geek3 : " << G3 << endl;

    return 0;
}

Output
The numerical value assigned to Geek1 : 0
The numerical value assigned to Geek2 : 1
The numerical value assigned to Geek3 : 2

Explanation: In the above code, the named constants like Geek1, Geek2, and Geek3 have assigned integral values such as 0, 1, 2 respectively while the output is given.



Previous Article
Next Article

Similar Reads

C++ Unions
In C++, a union is a user-defined datatype in which we can define members of different types of data types just like structures. But one thing that makes it different from structures is that the member variables in a union share the same memory location, unlike a structure that allocates memory separately for each member variable. The size of the u
5 min read
C Unions
The Union is a user-defined data type in C language that can contain elements of the different data types just like structure. But unlike structures, all the members in the C union are stored in the same memory location. Due to this, only one member can store data at the given instance. Syntax of Union in CThe syntax of the union in C can be divide
5 min read
Difference Between C Structures and C++ Structures
Let's discuss, what are the differences between structures in C and structures in C++? In C++, structures are similar to classes. Differences Between the C and C++ StructuresC Structures C++ Structures Only data members are allowed, it cannot have member functions.Can hold both: member functions and data members.Cannot have static members.Can have
6 min read
Internal Data Structures and Time Complexity Table of All the C++ STL Containers
As we all are using STL quite heavily in our programs in Interviews, Coding Contests. So knowing the Time complexity of the most frequently used operation and the data structure used behind the scene (in the internal implementation of the STL Library) is a must to know information. C++ STL Containers with Time Complexity &amp; Data Structure used B
2 min read
Policy based data structures in g++
The g++ compiler also supports some data structures that are not part of the C++ standard library. Such structures are called policy-based data structures. These data structures are designed for high-performance, flexibility, semantic safety, and conformance to the corresponding containers in std.To use these structures, the following lines must be
6 min read
Structures in C++
We often come around situations where we need to store a group of data whether of similar data types or non-similar data types. We have seen Arrays in C++ which are used to store set of data of similar data types at contiguous memory locations.Unlike Arrays, Structures in C++ are user defined data types which are used to store group of items of non
5 min read
Slack Bytes in Structures : Explained with Example
Structures: Structures are used to store the data belonging to different data types under the same variable name. An example of a structure is as shown below: struct STUDENT { char[10] name; int id; }; The memory space for the above structure would be allocated as shown below: Here we see that there is no empty spaces in between the members of the
3 min read
Array of Structures vs Array within a Structure in C
Both Array of Structures and Array within a Structure in C programming is a combination of arrays and structures but both are used to serve different purposes. Array within a Structure A structure is a data type in C that allows a group of related variables to be treated as a single unit instead of separate entities. A structure may contain element
5 min read
Array of Structures vs Array within a Structure in C++
In C++, an array of structure and an array within structure are used frequently used for data storage. Although they sound similar, they work pretty differently from each other. In this article, we will discuss the key differences between an array of structures and an array within structures and clarify the confusion. Array of Structures in C++An a
4 min read
Reduce Array and Maximize sum by deleting one occurrence of A[i] and all occurrences of A[i]+1 and A[i]-1
Given an array A[] having N positive integers, the task is to perform the following operations and maximize the sum obtained while reducing the array: Select an array element (say A[i]) and delete one occurrence of that element and add A[i] to the sum.Delete all the occurrences of A[i]-1 and A[i]+1.Perform these operations until the array is empty.
8 min read
Catching Base and Derived Classes as Exceptions in C++ and Java
An Exception is an unwanted error or hurdle that a program throws while compiling. There are various methods to handle an exception which is termed exceptional handling. Let's discuss what is Exception Handling and how we catch base and derived classes as an exception in C++: If both base and derived classes are caught as exceptions, then the catch
4 min read
fesetround() and fegetround() in C++ and their application
fesetround() It sets the specified floating point rounding direction or the "current rounding direction" which is expected to be one of the floating point rounding macros. It is used with rint(), nearbyint() and other rounding functions in C++. Syntax: int fesetround( int round ); where round can be FE_TONEAREST, FE_DOWNWARD, FE_UPWARD, FE_TOWARDZE
3 min read
Queries to insert, delete one occurrence of a number and print the least and most frequent element
Given Q queries of type 1, 2, 3 and 4 as described below. Type-1: Insert a number to the list.Type-2: Delete only one occurrence of a number if exists.Type-3: Print the least frequent element, if multiple elements exist then print the greatest among them.Type-4: Print the most frequent element, if multiple elements exist then print the smallest amo
14 min read
Even digits Sum and Odd digits sum divisible by 4 and 3 respectively
Given a number N represented as a string The task is to print 'Yes' if the sum of digits is even and is divisible by 4 or if the sum of digits is odd and is divisible by 3 otherwise 'No'.Examples: Input: 12345 Output: Yes Input: 894561 Output: Yes Below is the step by step algorithm: Calculate the sum of all digits.If the sum is even: Check if the
9 min read
Get first and last elements from Array and Vector in CPP
Given an array, find first and last elements of it. Input: {4, 5, 7, 13, 25, 65, 98} Output: First element: 4 Last element: 98 In C++, we can use sizeof operator to find number of elements in an array. // C++ Program to print first and last element in an array #include &lt;iostream&gt; using namespace std; int main() { int arr[] = { 4, 5, 7, 13, 25
2 min read
Similarities and Differences between Ruby and C++
There are many similarities between C++ and Ruby, some of them are: Just like C++, in Ruby… As in C++, public, private, and protected works similarly in Ruby also .Inheritance syntax is still only one character, but it’s &lt; instead of : in Ruby.The way ‘namespace’ is used in C++, in the similar way we may put our code into “modules” in ruby.There
3 min read
Given an array and two integers l and r, find the kth largest element in the range [l, r]
Given an unsorted array arr[] of n integers and an integer k, the task is to find the kth largest element in the given index range [l, r]Examples: Input: arr[] = {5, 3, 2, 4, 1}, k = 4, l = 1, r = 5 Output: 4 4 will be the 4th element when arr[0...4] is sorted.Input: arr[] = {1, 4, 2, 3, 5, 7, 6}, k = 3, l = 3, r = 6 Output: 5 Approach: A naive sol
11 min read
Longest subsequence possible that starts and ends with 1 and filled with 0 in the middle
Given a binary string s, the task is to find the length of the longest subsequence that can be divided into three substrings such that the first and third substrings are either empty or filled with 1 and the substring at the middle is either empty or filled with 0. Examples: Input: s = "1001" Output: 4 Explanation: The entire string can be divided
7 min read
Similarities and Difference between Java and C++
Nowadays Java and C++ programming languages are vastly used in competitive coding. Due to some awesome features, these two programming languages are widely used in industries as well as comepetitive programming . C++ is a widely popular language among coders for its efficiency, high speed, and dynamic memory utilization. Java is widely used in the
6 min read
Split a Binary String such that count of 0s and 1s in left and right substrings is maximum
Given a binary string, str of length N, the task is to find the maximum sum of the count of 0s on the left substring and count of 1s on the right substring possible by splitting the binary string into two non-empty substrings. Examples: Input: str = "000111" Output: 6 Explanation: Splitting the binary string into "000" and "111". Count of 0s in the
7 min read
Minimize array sum by replacing greater and smaller elements of pairs by half and double of their values respectively atmost K times
Given an array arr[] consisting of N positive integers and an integer K, the task is to find the minimum possible array sum that can be obtained by repeatedly selecting a pair from the given array and divide one of the elements by 2 and multiply the other element by 2, at most K times. Examples: Input: arr[] = {5, 1, 10, 2, 3}, K = 1 Output: 17 Exp
15+ min read
C++ Program to Rearrange array such that arr[i] &gt;= arr[j] if i is even and arr[i]&lt;=arr[j] if i is odd and j &lt; i
Given an array of n elements. Our task is to write a program to rearrange the array such that elements at even positions are greater than all elements before it and elements at odd positions are less than all elements before it.Examples: Input : arr[] = {1, 2, 3, 4, 5, 6, 7} Output : 4 5 3 6 2 7 1 Input : arr[] = {1, 2, 1, 4, 5, 6, 8, 8} Output : 4
3 min read
Sort and separate odd and even numbers in an Array using custom comparator
Given an array arr[], containing N elements, the task is to sort and separate odd and even numbers in an Array using a custom comparator. Example: Input: arr[] = { 5, 3, 2, 8, 7, 4, 6, 9, 1 }Output: 2 4 6 8 1 3 5 7 9 Input: arr[] = { 12, 15, 6, 2, 7, 13, 9, 4 }Output: 2 4 6 12 7 9 13 15 Approach: As we know std::sort() is used for sorting in increa
5 min read
Generate an array of given size with equal count and sum of odd and even numbers
Given an integer N, the task is to find an array of length N that contains same count of odd and even elements with an equal sum of even and odd elements in the array.Note: Print -1 if no such array is possible. Examples: Input: N = 4 Output: 1 2 5 4 Explanation: Even elements of the array - {2, 4}, S(even) = 6 Odd elements of the array - {1, 5}, S
8 min read
Find a number X such that (X XOR A) is minimum and the count of set bits in X and B are equal
Given two integers A and B, the task is to find an integer X such that (X XOR A) is minimum possible and the count of set bit in X is equal to the count of set bits in B.Examples: Input: A = 3, B = 5 Output: 3 Binary(A) = Binary(3) = 011 Binary(B) = Binary(5) = 101 The XOR will be minimum when M = 3 i.e. (3 XOR 3) = 0 and the number of set bits in
13 min read
C++ Program to Rearrange positive and negative numbers in O(n) time and O(1) extra space
An array contains both positive and negative numbers in random order. Rearrange the array elements so that positive and negative numbers are placed alternatively. Number of positive and negative numbers need not be equal. If there are more positive numbers they appear at the end of the array. If there are more negative numbers, they too appear in t
4 min read
Where and Why Do I Have to Put the 'template' and 'typename' Keywords?
In C++, we have a template keyword to define template classes or functions and allow them to operate with generic types. On the other hand, we have typename keyword which is used to specify that the identifier that follows is a type, particularly in template code to clarify the ambiguity but confusion arises as to where exactly we need to put these
3 min read
INT_MAX and INT_MIN in C/C++ and Applications
Most of the time, in competitive programming, there is a need to assign the variable, the maximum or minimum value that data type can hold, but remembering such a large and precise number comes out to be a difficult job. Therefore, C/C++ has certain macros to represent these numbers, so that these can be directly assigned to the variable without ac
7 min read
Comparing X^Y and Y^X for very large values of X and Y
Given two integer X and Y, the task is compare XY and YX for large values of X and Y.Examples: Input: X = 2, Y = 3 Output: 2^3 &lt; 3^2 23 &lt; 32Input: X = 4, Y = 5 Output: 4^5 &gt; 5^4 Naive approach: A basic approach is to find the values XY and YX and compare them which can overflow as the values of X and Y can be largeBetter approach: Taking l
4 min read
Change/add only one character and print '*' exactly 20 times
In the below code, change/add only one character and print '*' exactly 20 times. int main() { int i, n = 20; for (i = 0; i &lt; n; i--) printf("*"); getchar(); return 0; } Solutions:1. Replace i by n in for loop's third expression C/C++ Code #include &lt;iostream&gt; using namespace std; int main() { int i, n = 20; for (i = 0; i &lt; n; n--) cout
5 min read
Practice Tags :