Structures & Enumeration with C++ ?

I'd had the idea of having a note about Structures & Enumerations for a long time. Today, It's unveiling like this.
  • Structures
To begin with, I'd like to remind a little bit about the variables in C++. Variables in C++ can be initialized and used just like any other programming language. Look at the simple example below.

#include <stdio.h>

int main()
{
        int a = 1232;
        int b = 1234;
        printf("Value of a : %i \n",a);
        printf("Value of b : %i \n",b);
        return 0;
}
  


But, with the case sensitive nature of C++, any programmer should be having a large number of variables & large amount of lines of code in excessive programs. To avoid this, we used arrays in C++ like follows.

#include <stdio.h>
#define ARRAY_SIZE(array) (sizeof(arr)/sizeof(*arr))
int main()
{

        int arr[]={1232,1234,1236,1238};

        for(int a=0;a<=ARRAY_SIZE(arr);a++)
        {
                printf("Array Value : %i \n",arr[a]);
        }

        printf("Array Size : %i",ARRAY_SIZE(arr));

        return 0;
}


Since, arrays just allow us to store similar type of data. We move to Structures. Look at the example below.

#include <stdio.h>
struct var
{
        int a;
        double b;
        char c;
};

int main()
{
        var v;

        v.a=1232;
        v.b=123.2123;
        v.c='A';

        printf("Value of Variable is : %i \n",v.a);
        printf("Value of Variable is : %f \n",v.b);
        printf("Value of Variable is : %c \n",v.c);

        return 0;
}


In this example, it's obvious that Structures do leave the opportunity for us to store different types of data at the same time under the structure name which is useful.

  • Enumeration
Enumeration allows us to make our own variables & most importantly allows to permit a set of values for that variable. Look at the following example.

#include <iostream>
using namespace std;

enum days_of_week{Sun,Mon,Tue,Wed,Thu,Fri,Sat};

int main()
{
        days_of_week day1, day2;

        day1 = Thu;
        day2 = Mon;

        if(day1<day2)
        {
                cout<<"Day1 Comes before Day2"<<endl;
        }

        return 0;
}


As mentioned before, the importance of enumeration is that, it allows to create new data types that can take just restricted range of values &  those variables are stored as integers like the 'Concept of Array Index'.

#include<iostream>
using namespace std;

enum cards{spade=0,heart=3,club=1,diamond=2};

int main()
{
        cards c1,c2;

        c1 = spade;
        c2 = diamond;


        cout<<c1<<endl;
        cout<<c2<<endl;

        return 0;
}


In the above example all the default integer values of the variables are replaced with our own set of values. It makes Enumeration much more flexible to use. That's it about Structures & Enumeration ! Enjoy C++ !

No comments: