enum shape {circle=10, square, rectangle};
shape a = circle;
shape b = square;
shape c = rectangle;
enum gender {female, male};
The same functionality can be achieved using macros.
However, macros have global scope.
Enums could have local(Inside a function) or global(if outside of all functions) scope.
Typedef:
struct node
{
int data;
node *link;
};
typedef node N;
N *root = new N;
root->data = 10;
root->link = NULL;
cout << root->data << "\t" << root->link;
Bit Fields:
struct employee
{
unsigned gender: 1; //The colon tells the compiler that we are talking about the bit field
unsigned id: 4;
unsigned status: 3;
unsigned efficient: 2;
};
enum gender {female, mae};
enum id {One,Two};
enum status {Single, Married, Committed};
enum efficient {Yes, No};
int main()
{
gender gg = female;
id gi = One;
status gs = Committed;
efficient ge = Yes;
employee e;
e.gender = gg;
e.id = gi;
e.status = gs;
e.efficient = ge;
cout << e.gender << endl;
cout << e.id << endl;
cout << e.status << endl;
cout << e.efficient << endl;
getch();
return 0;
}
Function Pointers:
void display()
{
cout << "Display\n";
}
int main()
{
void (*fptr)(); //Pointer to a function
fptr = display; //Pointer now contains the address of the function
cout << "Address of the function: " << fptr << endl; //Outputing the address of the function
(*fptr)(); //Invoking the function; //Invoking the function
getch();
return 0;
}
Useful for: Dynamically binding a function to the pointer. Dynamically invoking the function too.
Function returning pointers:
int* display() //This function is returning a pointer.
{
cout << "Display\n";
static int i = 30;
return(&i); //It will actually be returning the address to an integer
}
int main()
{
int *p;
p = display();//The address is populated in a pointer variable
cout << "Address : " << p << "\tValue: " << *p;
getch();
return 0;
}
Union:
typedef union
{
int i;
char c[4];
}test; //This union is not of 8 bytes(4 for int and 4 for chars). It is of 4 bytes only.
int main()
{
test t;
t.c[0] = 'A'; //The value assigned to the characters will get assigned to the integer i accordingly
t.c[1] = 'B'; //As the 4 bytes of the characters are shared by the int too.
t.c[2] = 'C';
t.c[3] = 'D';
//t.i; // We can't assign value to both the data variables at the same time.
//This is useful in hardware when sometimes we have to read only 1 value or all the 4 values
cout << t.c[0] << "\t" << t.c[1] << "\t" << t.c[2] << "\t" << t.c[3] << endl;
cout << t.i << endl;
getch();
return 0;
}
No comments:
Post a Comment