Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 12

Unions

C Union is also like structure, i.e. collection of different data types which are
grouped together. Each element in a union is called member.

 Union and structure in C are same in concepts, except allocating memory


for their members.
 Structure allocates storage space for all its members separately.
 Whereas, Union allocates one common storage space for all its members
 We can access only one member of union at a time.
 We can’t access all member values at the same time in union. But,
structure can access all member values at the same time.
  Union allocates one common storage space for all its members.
Where as Structure allocates storage space for all its members separately.
 Many union variables can be created in a program and memory will be
allocated for each union variable separately.

Below table will help you how to form a C union, declare a union, initializing
and accessing the members of the union.

Type Using normal variable


Syntax union tag_name
{
data type var_name1;
data type var_name2;
data type var_name3;
};

Example union student
{
int  mark;
char name[10];
float average;
};

Declaring union variable union student report;


Initializing union variable union student report = {100, “Mani”, 99.5};
Accessing union members report.mark
report.name
report.average
/* unions example program*/
#include <stdio.h>
#include <string.h>
union student // step 1
{
char name[20];
char subject[20];
float percentage;
};
int main()
{
union student record1; // step 1

// assigning values to record1 union variable


strcpy(record1.name, "Raju");
strcpy(record1.subject, "Maths");
record1.percentage = 86.50;
printf("Union record1 values example\n");
printf(" Name : %s \n", record1.name); // step 3
printf(" Subject : %s \n", record1.subject);
printf(" Percentage : %f \n\n", record1.percentage);
return 0;
}
OUTPUT:
Name :
Subject :
Percentage : 86.500000
NOTE: We can access only one member of union at a time. We can’t access all.

Major advantages of using unions


Major advantages of using unions are:
1. Efficient use of memory as it does not use memory space for its all members
2. It requires memory space for its largest member only.
3. Same memory space can be interpreted for different members of the union.
4. You can access one member at a time in the union.
5. It occupies less memory compared to structure.
Difference between Structures and Unions:

Structure Union
1. The keyword  struct is used to 1. The keyword union is used to define
define a structure a union.
2. When a variable is associated with 2. When a variable is associated with a
a structure, the compiler allocates union, the compiler allocates
the memory for each member. the memory by considering the size
of the largest memory.
3. The size of structure is greater than 3. Size of union is equal to the size of
or equal to the sum of sizes of its largest member.
members.
4. Each member within a structure is 4. Memory allocated is shared
assigned unique storage area of by individual members of union.
location.
5. The address of each member will 5. The address is same for all the
be in ascending order. This members of a union. This
indicates that memory for each indicates that every member begins
member will start at different offset at the same offset value.
values.
6. Altering the value of a member will 6. Altering the value of any of the
not affect other members of member will alter other member
the structure. values.
7.  Individual member can be accessed 7. Only one member can be accessed at
at a time a time.
8. Several members of a structure can 8. Only the first member of a union can
initialize at once. be initialized.
Enumerated Data type in C:
In C programming, An Enumerated Data type (also called enum) is a user defined
data type that consists of integral constants.

An Enumerated Data type is a special class that represents a group of constants. 

To define enums, the enum keyword is used.

enum flag {const 1, const 2, ..., const N };

By default, const 1 is 0, const 2 is 1 and so on.

e.g:
enum week {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};

enum year{Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec}

You can change default values of enum elements during declaration (if necessary).

// Changing default values of enum constants

Enum suit {
club = 0,
diamonds = 10,
hearts = 20,
spades = 3,
};

Enumerated Type Declaration:

When you define an enum type, the blueprint for the variable is created. Here's how
you can create variables of enum types.

enum week today;  creating today variable of enum week type

enum year month  creating month variable of enum year type


Example program on Enum

// Enum data type demo

#include <stdio.h>

enum week {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};

int main()

enum week today; // creating today variable of enum week type

today = Wednesday;

printf("Day %d",today+1);

return 0;

Output: Day 4

Example2:
// Another example program to demonstrate working of enum in C

#include<stdio.h>

enum year{Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec};

int main()

int i;

for (i=Jan; i<=Dec; i++)

printf("%d ", i);

return 0;

Output:

0 1 2 3 4 5 6 7 8 9 10 11
Pointers in C:
Variable Address in C:

Consider a variable  is declared as int num = 10; the compiler allocates memory.
So, &num  will give you its address in the memory.

While using scanf("%d", &num); ,the input value 10 is stored at the address of
num.
When the following statements are used we will get the output as:

printf("num: %d\n", num);


printf("address of num: %d", &num);

Output
num: 10
address of num: 8280

Pointer variable:
A pointer is a variable that stores the address of another variable.

Unlike other variables that hold values, pointer holds the address of a variable.

Pointers are used to access memory and manipulate the address.

For example, an integer variable holds (or you can say stores) an integer value,
however an integer pointer holds the address of a integer variable. I

A pointer gets stored in another memory location.

For example, int a;


int *ptr;
ptr= &a;
Advantages of using pointers:

Below we have listed a few advantages of using pointers:

1. Pointers are more efficient in handling Arrays and Structures.


2. Pointers allow references to function /passing of function as arguments to
other functions.
3. It reduces length of the program and its execution time as well.
4. It allows C language to support Dynamic Memory management.

5. Program execution speed is increased.

6. Pointers make the programs simple and reduce their length.

7. Pointers are helpful in traversing through arrays and character strings. The
strings are also arrays of characters terminated by the null character ('\O').

8. Pointers also act as references to different types of objects such as variables,


arrays, functions, structures, etc.

9. Storage of strings through pointers saves memory space.

10. Pointers are used to construct different data structures such as linked lists,
queues, stacks, etc.
Declaration of C Pointer variable:
General syntax of pointer declaration is,
datatype *pointer_name;

Data type of a pointer must be same as the data type of the variable to which the
pointer variable is pointing.
Here are a few examples:
int *ip // pointer to integer variable
float *fp; // pointer to float variable
double *dp; // pointer to double variable
char *cp; // pointer to char variable

Initialization of C Pointer variable:


 Pointer Initialization is ,assigning address of a variable to a pointer variable.
 Pointer variable can only contain address of a variable of the same data type.
 The address operator & is used to determine the address of a variable.
int a = 10;
int *ptr; //pointer declaration
ptr = &a; //pointer initialization
Using the pointer or Dereferencing of Pointer:
Once a pointer has been assigned the address of a variable, to access the value of
the variable, pointer is dereferenced, using the indirection/dereferencing operator *.

#include <stdio.h>
int main()
{
int a, *p; // declaring the variable and pointer
a = 10;
p = &a; // initializing the pointer

printf("%d", *p); //this will print the value of 'a'

printf("%d", *&a); //this will also print the value of 'a'

printf("%u", &a); //this will print the address of 'a'

printf("%u", p); //this will also print the address of 'a'

printf("%u", &p); //this will print the address of 'p'


return 0;}
Pointer Arithmetic in C

If you want to have complete knowledge of pointers, pointer arithmetic is very


important to understand. In this topic we will study how the memory addresses
change when you increment a pointer.

16 bit Machine (Turbo C)

In a 16 bit machine, size of all types of pointer, be it int*, float*, char* or double* is


always 2 bytes. But when we perform any arithmetic function like increment on a
pointer, changes occur as per the size of their primitive data type.

Size of datatypes on 16-bit Machine:

Type Size (in bytes)

int or signed int 2

char 1

long 4

float 4

double 8

long double 10

Examples for Pointer Arithmetic


Now lets take a few examples and understand this more clearly.
int* i;
i++;
In the above case, pointer will be of 2 bytes. And when we increment it, it
will increment by 2 bytes because int is also of 2 bytes.

float* i;
i++;
In this case, size of pointer is still 2 bytes initially. But now, when we
increment it, it will increment by 4 bytes because float datatype is of 4
bytes.

double* i;
i++;
Similarly, in this case, size of pointer is still 2 bytes. But now, when we
increment it, it will increment by 8 bytes because its data type is double.

32 bit Machine (Visual Basic C++)

The concept of pointer arithmetic remains exact same, but the size of
pointer and various datatypes is different in a 32 bit machine. Pointer in
32 bit machine is of 4 bytes.

And, following is a table for Size of datatypes on 32-bit Machine :

Type Size (in bytes)

int or signed int 4

char 2

long 8

float 8

double 16
Note: We cannot add two pointers. This is because pointers contain
addresses, adding two addresses makes no sense.

But we can subtract two pointers. This is because difference between


two pointers gives the number of elements of its data type that can be
stored between the two pointers.
Program for pointer arithmetic(32-bit machine)

#include <stdio.h>

int main()

int m = 5, n = 10, o = 0;

int *p1;

int *p2;

int *p3;

p1 = &m; //printing the address of m

p2 = &n; //printing the address of n

printf("p1 = %d\n", p1);

printf("p2 = %d\n", p2);

o = *p1+*p2;

printf("*p1+*p2 = %d\n", o);//point 1

p3 = p1-p2;

printf("p1 - p2 = %d\n", p3); //point 2

p1++;

printf("p1++ = %d\n", p1); //point 3

p2--;

printf("p2-- = %d\n", p2); //point 4

return 0;

}
Output:

p1 = 2680016

p2 = 2680012

*p1+*p2 = 15

p1-p2 = 1

p1++ = 2680020

p2-- = 2680008

Explanation of the above program:

1. Point 1: Here, * means 'value at the given address'. Thus, it adds


the value of m and n which is 15.
2. Point 2: It subtracts the addresses of the two variables and then
divides it by the size of the pointer datatype (here integer, which
has size of 4 bytes) which gives us the number of elements of
integer data type that can be stored within it.
3. Point 3: It increments the address stored by the pointer by the size
of its datatype(here 4).
4. Point 4: It decrements the address stored by the pointer by the
size of its datatype(here 4).

You might also like