0% found this document useful (0 votes)
9 views

cccc

This document provides an overview of pointers in C programming, explaining their declaration, initialization, and various types such as null, void, and wild pointers. It discusses pointer arithmetic, access methods, and the pros and cons of using pointers, along with their applications in dynamic memory allocation and data structures. The document also includes code examples to illustrate the concepts discussed.

Uploaded by

DAH Gaming
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

cccc

This document provides an overview of pointers in C programming, explaining their declaration, initialization, and various types such as null, void, and wild pointers. It discusses pointer arithmetic, access methods, and the pros and cons of using pointers, along with their applications in dynamic memory allocation and data structures. The document also includes code examples to illustrate the concepts discussed.

Uploaded by

DAH Gaming
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Unit IV

Advance Programming in C

Pointer:
The pointers perform the function of storing the addresses of other variables in the program.

These variables could be of any type- char, int, function, array, or other pointers.

The pointer sizes depend on their architecture. (For ex. the size of a pointer in the 32-bit architecture
is 2 bytes.)
Let us look at an example where we define a pointer storing an integer’s address in a program.

int x = 10;

int* p = &x;

Here, the variable p is of pointer type, and it is pointing towards the address of the x variable, which
is of the integer type.

Declaration of a Pointer
Just like the variables, we also have to declare the pointers in C before we use them in any program.
2

We can name these pointers anything that we like, as long as they abide by the naming rules of the C
language. Normally, the declaration of a pointer would take a form like this: data_type *
name_of_pointer_variable;

Note that here,

● The data_type refers to this pointer’s base type in the variable of C. It indicates which type of
variable is the pointer pointing to in the code.
● The asterisk ( * ) is used to declare a pointer. It is an indirection operator, and it is the same
asterisk that we use in multiplication.

We can declare pointers in the C language with the use of the asterisk symbol ( * ). It is also called
the indirection pointer, as we use it for dereferencing any pointer. Here is how we use it:

int *q; // a pointer q for int data type

char *x; // a pointer x for char data type

The Initialization of a Pointer


We use the & (ampersand) operator to get the variable’s address in the program. We place the & just
before that variable’s name whose address we require. Here is the syntax that we use for the
initialisation of a pointer,

Syntax of Pointer Initialization

pointer = &variable;

As we can assess in the figure shown above, the pointer variable is storing the digit variable’s
3

address, named fff4. This digit variable’s value is equal to 100. But aaa3 is the pointer variable’s
address (variable r).

Here, we can print the r pointer variable’s value using the indirection pointer ( * ). We will look at an
example for the same, as explained in the figure mentioned above.

#include<stdio.h>

int main(){

int digit=100;

int *r;

r=&digit; // for storing the address of the digit variable in the program

printf(“The address of the variable r is equal to %x \n”,r); // pointer r contains the digit variable’s
address, and thus, printing the variable r gives us the address of the digit.

printf(“The value of the variable r is equal to %d \n”,*r); // We are using * to dereference the pointer,
and thus, printing *r, would give the value that is stored at that address which is contained by r.

return 0;

he output of the code mentioned above would be like this:

The address of the variable r is equal to fff4

The value of the variable r is equal to 100

Use of Pointers in C
Here is a summary of how we use the following operators for the pointers in any program:

Operator Name Uses and Meaning of Operator

* Asterisk Declares a pointer in a program.

Returns the referenced variable’s value.


4

& Ampersand Returns a variable’s address

The Pointer to an Array


Here is an example to illustrate the same,

int arr [20];

int *q [20] = &arr; // The q variable of the pointer type is pointing towards the integer array’s address
or the address of arr.

The Pointer to a Function


Here is an example to illustrate the same,

void display (int);

void(*q)(int) = &show; // The q pointer is pointing towards the function’s address in the program

The Pointer to a Structure


Here is an example to illustrate the same,

struct str {

int x;

float y;

}ref;

struct str *q = &ref;


5

void apoo()

int var = 10;

// declare pointer variable

int* ptr;

// data type of ptr and var must be same

ptr = &var;

// assign the address of a variable to a pointer

printf("Value at ptr = %p \n", ptr);

printf("Value at var = %d \n", var);

printf("Value at *ptr = %d \n", *ptr);

// Driver program
6

int main()

apoo();

return 0;

Types of Pointers
There are various types of pointers that we can use in the C language. Let us take a look at the most
important ones.

The Null Pointer


The null pointer has a value of 0. To create a null pointer in C, we assign the pointer with a null value
during its declaration in the program. This type of method is especially useful when the pointer has
no address assigned to it. Let us take a look at a program that illustrates how we use the null pointer:

#include <stdio.h>

int main()

int *a = NULL; // the null pointer declaration

printf(“Value of the variable a in the program is equal to :\n%x”,a);

return 0;

The output obtained out of the program mentioned above will be:

Value of the variable a in the program is equal to: 0

The Void Pointer


The void pointer is also known as the generic pointer in the C language. This pointer has no standard
7

data type, and we create it with the use of the keyword void. The void pointer is generally used for
the storage of any variable’s address. Let us take a look at a program that illustrates how we use the
void pointer in a C program:

#include <stdio.h>

int main()

void *q = NULL; // the void pointer of the program

printf(“Size of the void pointer in the program is equal to : %d\n”,sizeof(q));

return 0;

The output obtained out of the program mentioned above will be:

Size of the void pointer in the program is equal to : 4

The Wild Pointer


We can call a pointer a wild pointer if we haven’t initialized it with anything. Such wild pointers are
not very efficient in a program, as they may ultimately point towards some memory location that is
unknown to us. It will ultimately lead to some problems in the program, and then, it will crash. Thus,
you must be very careful when using wild pointers in a program. Let us take a look at a program that
illustrates how we use the wild pointer in a C program:

#include <stdio.h>

int main()

int *w; // the wild pointer in the program

printf(“\n%d”,*w);

return 0;

}
8

The output obtained out of the program mentioned above will be a compile-time error.

Here are a few more types of pointers that you can find in the C programs:

● Near pointer
● Complex pointer
● Huge pointer
● Far pointer
● Dangling pointer

Accessing Pointers- Indirectly and Directly


There are basically two ways in which a program can access a variable content and then manipulate
it:

● Direct Access: In this case, we use the variable name in the program directly.
● Indirect Access: In this case, we use some pointers to the variables in the program.

Let us take a look at a program to understand this better. Consider the below program:

#include <stdio.h>

/* Declaration and initialization of an int variable in the program */

int variable = 1;

/* Declaration of the pointer to the int variable */

int *ptr;

int main( void )

/* Initialization of ptr to the point to the variable */

ptr = &variable;

/* Accessing var indirectly and directly */

printf(“\nThe direct access of the variable would be = %d”, variable);

printf(“\nThe indirect access of the variable would be = %d”, *ptr);


9

/* Displaying of the address of the variable in both the ways */

printf(“\n\nOutput of the address of the variable would be = %d”, &variable);

printf(“\nOutput of the address of the variable would be = %d\n”, ptr);

/*changing of the content of the variable through the ptr pointer in the program*/

*ptr=48;

printf(“\nThe indirect access of the variable would be = %d”, *ptr);

return 0;

The compilation of this program devoid of errors would generate an output like this:

The direct access of the variable would be = 1

The indirect access of the variable would be = 1

Output of the address of the variable would be = 4202496

Output of the address of the variable would be = 4202496

The indirect access of the variable would be = 48

Pros of using Pointers in C


● Pointers make it easy for us to access locations of memory.
● They provide an efficient way in which we can access the elements present in the structure
of an array.
● We can use pointers for dynamic allocation and deallocation of memory.
● These are also used to create complex data structures, like the linked list, tree, graph, etc.
● It reduces the code and thus improves the overall performance. We can use it to retrieve the
strings, trees, and many more. We can also use it with structures, arrays, and functions.
● We can use the pointers for returning various values from any given function.
● One can easily access any location of memory in the computer using the pointers.

Cons of Pointers in C
10

● The concept of pointers is a bit tricky to understand.


● These can lead to some errors like segmentation faults, accessing of unrequired memory
locations, and many more.
● A pointer may cause corruption of memory if we provide it with an incorrect value.
● Pointers in a program can lead to leakage of memory.
● As compared to all the other variables, pointers are somewhat slower.
● Some programmers might find it very tricky to deal with pointers in a program. It is their
responsibility to use these pointers and manipulate them carefully.

Applications of Pointers in C
There are various uses of the pointers in C language. Let us look at some of them:

1. Dynamic allocation of memory: We can allocate the memory dynamically in C language when we
use the calloc() and malloc() functions. The pointers are primarily used in such cases.

2. Structures, Functions, and Arrays: We generally use the pointers in the C language in the cases of
structures, functions, and arrays. Here, the pointers help in reducing the code and improving the
program’s performance.

The & Address of Operator in C


This operator basically returns the variable’s address. But keep in mind that we must use the %u if
we want to display the variable’s address.

#include<stdio.h>

int main(){

int digit=100;

printf(“The value of the digit is equal to %d and the address of the digit is equal to %u”,digit,&digit);

return 0;

The output of the program mentioned above would be like this:

The value of the digit is equal to 100 and the address of the digit is equal to fff4
11

Pointer Arithmetics in C:

Pointer Arithmetic is the set of valid arithmetic operations that can be performed
on pointers.
These operations are:

1. Increment/Decrement of a Pointer
2. Addition of integer to a pointer
3. Subtraction of integer to a pointer
4. Subtracting two pointers of the same type
5. Comparison of pointers

1. Increment/Decrement of a Pointer
Increment: It is a condition that also comes under addition. When a pointer is
incremented, it actually increments by the number equal to the size of the data
type for which it is a pointer.

For Example:
If an integer pointer that stores address 1000 is incremented, then it will
increment by 4(size of an int), and the new address will point to 1004. While if a
float type pointer is incremented then it will increment by 4(size of a float) and
the new address will be 1004.

Decrement: It is a condition that also comes under subtraction. When a pointer is


decremented, it actually decrements by the number equal to the size of the data
type for which it is a pointer.

For Example:
If an integer pointer that stores address 1000 is decremented, then it will
decrement by 4(size of an int), and the new address will point to 996. While if a
float type pointer is decremented then it will decrement by 4(size of a float) and
the new address will be 996.
12

Example:

#include <stdio.h>

int main()

int a = 22;

int *p = &a;

printf("p = %u\n", p); // p = 6422288

p++;

printf("p++ = %u\n", p); //p++ = 6422292 +4 // 4 bytes

p--;

printf("p-- = %u\n", p); //p-- = 6422288 -4 // restored to original value


13

float b = 22.22;

float *q = &b;

printf("q = %u\n", q); //q = 6422284

q++;

printf("q++ = %u\n", q); //q++ = 6422288 +4 // 4 bytes

q--;

printf("q-- = %u\n", q); //q-- = 6422284 -4 // restored to original value

char c = 'a';

char *r = &c;

printf("r = %u\n", r); //r = 6422283

r++;

printf("r++ = %u\n", r); //r++ = 6422284 +1 // 1 byte

r--;

printf("r-- = %u\n", r); //r-- = 6422283 -1 // restored to original value

return 0;

2. Addition of Integer to Pointer


When a pointer is added with an integer value, the value is first multiplied by the
size of the data type and then added to the pointer.

For Example:
Consider the same example as above where the ptr is an integer pointer that
stores 1000 as an address. If we add integer 5 to it using the expression, ptr = ptr
14

+ 5, then, the final address stored in the ptr will be ptr = 1000 + sizeof(int) * 5 =
1020.

#include <stdio.h>

// Driver Code
int main()
{
// Integer variable
int N = 4;

// Pointer to an integer
int *ptr1, *ptr2;

// Pointer stores the address of N


ptr1 = &N;
ptr2 = &N;

printf("Pointer ptr2 before Addition: ");


15

printf("%p \n", ptr2);

// Addition of 3 to ptr2
ptr2 = ptr2 + 3;
printf("Pointer ptr2 after Addition: ");
printf("%p \n", ptr2);

return 0;
}

3. Subtraction of Integer to Pointer


When a pointer is subtracted with an integer value, the value is first multiplied
by the size of the data type and then subtracted from the pointer similar to
addition.

For Example:
Consider the same example as above where the ptr is an integer pointer that
stores 1000 as an address. If we subtract integer 5 from it using the expression,
ptr = ptr – 5, then, the final address stored in the ptr will be ptr = 1000 –
sizeof(int) * 5 = 980.
16

4. Subtraction of Two Pointers


The subtraction of two pointers is possible only when they have the same data
type. The result is generated by calculating the difference between the addresses
of the two pointers and calculating how many bits of data it is according to the
pointer data type. The subtraction of two pointers gives the increments between
the two pointers.

For Example:
Two integer pointers say ptr1(address:1000) and ptr2(address:1004) are
subtracted. The difference between addresses is 4 bytes. Since the size of int is
4 bytes, therefore the increment between ptr1 and ptr2 is given by (4/4) = 1.

#include <stdio.h>

int main()
17

int x = 6; // Integer variable declaration

int N = 4;

// Pointer declaration

int *ptr1, *ptr2;

ptr1 = &N; // stores address of N

ptr2 = &x; // stores address of x

printf(" ptr1 = %u, ptr2 = %u\n", ptr1, ptr2);

x = ptr2 - ptr1;

printf("Subtraction of ptr1 "

"& ptr2 is %d\n",

x);

return 0;

}
18

5. Comparison of Pointers
We can compare the two pointers by using the comparison operators in C. We
can implement this by using all operators in C >, >=, <, <=, ==, !=. It returns true
for the valid condition and returns false for the unsatisfied condition.

1. Step 1: Initialize the integer values and point these integer values to the
pointer.
2. Step 2: Now, check the condition by using comparison or relational
operators on pointer variables.
3. Step 3: Display the output.

#include <stdio.h>

int main()

int arr[5];

int* ptr1 = &arr;

int* ptr2 = &arr[0];


19

if (ptr1 == ptr2) {

printf("Pointer to Array Name and First Element "

"are Equal.");

else {

printf("Pointer to Array Name and First Element "

"are not Equal.");

return 0;

Passing Pointers to Functions in C:


Passing the pointers to the function means the memory location of the variables
is passed to the parameters in the function, and then the operations are
performed. The function definition accepts these addresses using pointers,
addresses are stored using pointers.

Arguments Passing without pointer


When we pass arguments without pointers the changes made by the function
would be done to the local variables of the function.
20

Below is the C program to pass arguments to function without a pointer:


#include <stdio.h>

void swap(int a, int b)


{
int temp = a;
a = b;
b = temp;
}

// Driver code
int main()
{
int a = 10, b = 20;
swap(a, b);
printf("Values after swap function are: %d, %d",
a, b);
return 0;
}
utput
Values after swap function are: 10, 20

Arguments Passing with pointers


A pointer to a function is passed in this example. As an argument, a pointer is
passed instead of a variable and its address is passed instead of its value. As a
result, any change made by the function using the pointer is permanently stored
at the address of the passed variable. In C, this is referred to as call by reference.

Below is the C program to pass arguments to function with pointers:

C
21

// C program to swap two values

// without passing pointer to

// swap function.

#include <stdio.h>

void swap(int* a, int* b)

int temp;

temp = *a;
22

*a = *b;

*b = temp;

// Driver code

int main()

int a = 10, b = 20;

printf("Values before swap function are: %d, %d\n",

a, b);
23

swap(&a, &b);

printf("Values after swap function are: %d, %d",

a, b);

return 0;

Output

Values before swap function are: 10, 20


Values after swap function are: 20, 10

C – Pointer to Pointer:
The pointer to a pointer in C is used when we want to store the address of
another pointer. The first pointer is used to store the address of the variable. And
the second pointer is used to store the address of the first pointer. That is why
they are also known as double-pointers. We can use a pointer to a pointer to
change the values of normal pointers or create a variable-sized 2-D array. A
double pointer occupies the same amount of space in the memory stack as a
normal pointer.
24

Declaration of Pointer to a Pointer in C


Declaring Pointer to Pointer is similar to declaring a pointer in C. The difference is
we have to place an additional ‘*’ before the name of the pointer.
data_type_of_pointer **name_of_variable = & normal_pointer_variable;

int val = 5;

int *ptr = &val; // storing address of val to pointer ptr.

int **d_ptr = &ptr; // pointer to a pointer declared


// which is pointing to an integer.

The first pointer ptr1 stores the address of the variable and the second pointer
ptr2 stores the address of the first pointer.

#include <stdio.h>

int main()

int var = 789;


25

// pointer for var

int* ptr2;

// double pointer for ptr2

int** ptr1;

// storing address of var in ptr2

ptr2 = &var;

// Storing address of ptr2 in ptr1

ptr1 = &ptr2;

// Displaying value of var using

// both single and double pointers

printf("Value of var = %d\n", var);

printf("Value of var using single pointer = %d\n", *ptr2);

printf("Value of var using double pointer = %d\n", **ptr1);

return 0;

}
26

Application of Double Pointers in C


Following are the main uses of pointer to pointers in C:

● They are used in the dynamic memory allocation of multidimensional


arrays.
● They can be used to store multilevel data such as the text document
paragraph, sentences, and word semantics.
● They are used in data structures to directly manipulate the address of
the nodes without copying.
● They can be used as function arguments to manipulate the address
stored in the local pointer.
27

Structure in C:

The structure in C is a user-defined data type that can be used to group items of
possibly different types into a single type. The struct keyword is used to define
the structure in the C programming language. The items in the structure are
called its member and they can be of any valid data type.
C Structure Declaration
We have to declare structure in C before using it in our program. In structure
declaration, we specify its member variables along with their datatype. We can
use the struct keyword to declare the structure in C using the following syntax:

Syntax

struct structure_name {

data_type member_name1;
28

data_type member_name1;

....

....
};

C Structure Definition
To use structure in our program, we have to define its instance. We can do that
by creating variables of the structure type. We can define structure variables
using two methods:

1. Structure Variable Declaration with Structure Template

struct structure_name {

data_type member_name1;

data_type member_name1;

....

....
}variable1, varaible2, ...;

2. Structure Variable Declaration after Structure Template

// structure declared beforehand


struct structure_name variable1, variable2, .......;

Access Structure Members


We can access structure members by using the ( . ) dot operator.

Syntax

structure_name.member1;
strcuture_name.member2;

Initialize Structure Members


Structure members cannot be initialized with the declaration. For example, the
following C program fails in the compilation.
29

struct Point

int x = 0; // COMPILER ERROR: cannot initialize members here

int y = 0; // COMPILER ERROR: cannot initialize members here


};

The reason for the above error is simple. When a datatype is declared, no
memory is allocated for it. Memory is allocated only when variables are created.

We can initialize structure members in 3 ways which are as follows:

1. Using Assignment Operator.


2. Using Initializer List.
3. Using Designated Initializer List.

1. Initialization using Assignment Operator

struct structure_name str;

str.member1 = value1;

str.member2 = value2;

str.member3 = value3;

.
.

2. Initialization using Initializer List

struct structure_name str = { value1, value2, value3 };

In this type of initialization, the values are assigned in sequential order as they
are declared in the structure template.

3. Initialization using Designated Initializer List

Designated Initialization allows structure members to be initialized in any order.


30

This feature has been added in the C99 standard.


struct structure_name str = { .member1 = value1, .member2 = value2, .member3 = value3 };

Example:

#include <stdio.h>

#include <string.h>

// create struct with person1 variable

struct Person {

char name[50];

int citNo;

float salary;

} person1;

int main() {

// assign value to name of person1

strcpy(person1.name, "George Orwell");

// assign values to other person1 variables

person1.citNo = 1984;

person1. salary = 2500;

// print struct variables

printf("Name: %s\n", person1.name);


31

printf("Citizenship No.: %d\n", person1.citNo);

printf("Salary: %.2f", person1.salary);

return 0;

Output

Name: George Orwell

Citizenship No.: 1984

Salary: 2500.00

Keyword typedef
We use the typedef keyword to create an alias name for data types. It is commonly used with
structures to simplify the syntax of declaring variables.

For example, let us look at the following code:

struct Distance{

int feet;

float inch;

};

int main() {

struct Distance d1, d2;

}
32

We can use typedef to write an equivalent code with a simplified syntax:

typedef struct Distance {

int feet;

float inch;

} distances;

int main() {

distances d1, d2;

#include <stdio.h>

#include <string.h>

// struct with typedef person

typedef struct Person {

char name[50];

int citNo;

float salary;

} person;

int main() {

// create Person variable

person p1;
33

// assign value to name of p1

strcpy(p1.name, "George Orwell");

// assign values to other p1 variables

p1.citNo = 1984;

p1. salary = 2500;

// print struct variables

printf("Name: %s\n", p1.name);

printf("Citizenship No.: %d\n", p1.citNo);

printf("Salary: %.2f", p1.salary);

return 0;

Output

Name: George Orwell

Citizenship No.: 1984

Salary: 2500.00

Nested Structures:
You can create structures within a structure in C programming. For example,

struct complex {

int imag;
34

float real;

};

struct number {

struct complex comp;

int integers;

} num1, num2;

Suppose, you want to set imag of num2 variable to 11. Here's how you can do it:

num2.comp.imag = 11;

Example 3: C Nested Structures


#include <stdio.h>

struct complex {

int imag;

float real;

};

struct number {

struct complex comp;

int integer;

} num1;

int main() {
35

// initialize complex variables

num1.comp.imag = 11;

num1.comp.real = 5.25;

// initialize number variable

num1.integer = 6;

// print struct variables

printf("Imaginary Part: %d\n", num1.comp.imag);

printf("Real Part: %.2f\n", num1.comp.real);

printf("Integer: %d", num1.integer);

return 0;

Output:

Imaginary Part: 11

Real Part: 5.25

Integer: 6

Passing structs to functions:


#include <stdio.h>

struct student {

char name[50];

int age;
36

};

// function prototype

void display(struct student s);

int main() {

struct student s1;

printf("Enter name: ");

// read string input from the user until \n is entered

// \n is discarded

scanf("%[^\n]%*c", s1.name);

printf("Enter age: ");

scanf("%d", &s1.age);

display(s1); // passing struct as an argument

return 0;

void display(struct student s) {

printf("\nDisplaying information\n");
37

printf("Name: %s", s.name);

printf("\nAge: %d", s.age);

Output

Enter name: Bond

Enter age: 13

Displaying information

Name: Bond

Age: 13

C Pointers to struct
Here's how you can create pointers to structs.

struct name {

member1;

member2;

};

int main()

struct name *ptr, Harry;

}
38

Here, ptr is a pointer to struct.

Example: Access members using Pointer


To access members of a structure using pointers, we use the -> operator.

#include <stdio.h>

struct person

int age;

float weight;

};

int main()

struct person *personPtr, person1;

personPtr = &person1;

printf("Enter age: ");

scanf("%d", &personPtr->age);

printf("Enter weight: ");

scanf("%f", &personPtr->weight);

printf("Displaying:\n");

printf("Age: %d\n", personPtr->age);


39

printf("weight: %f", personPtr->weight);

return 0;

C Unions
A union is a user-defined type similar to structs in C except for one key
difference.

Structures allocate enough space to store all their members, whereas unions
can only hold one member value at a time.

How to define a union?


We use the union keyword to define unions. Here's an example:

union car

char name[50];

int price;

};

The above code defines a derived type union car.

Create union variables


When a union is defined, it creates a user-defined type. However, no memory
40

is allocated. To allocate memory for a given union type and work with it, we
need to create variables.

Here's how we create union variables.

union car

char name[50];

int price;

};

int main()

union car car1, car2, *car3;

return 0;

Another way of creating union variables is:

union car

char name[50];

int price;

} car1, car2, *car3;

In both cases, union variables car1, car2, and a union pointer car3 of union car type
41

are created.

Access members of a union

We use the . operator to access members of a union. And to access pointer


variables, we use the -> operator.

In the above example,

● To access price for car1, car1.price is used.

● To access price using car3, either (*car3).price or car3->price can be used.

Difference between unions and structures


Let's take an example to demonstrate the difference between unions and
structures:

#include <stdio.h>

union unionJob

//defining a union

char name[32];

float salary;

int workerNo;

} uJob;

struct structJob

{
42

char name[32];

float salary;

int workerNo;

} sJob;

int main()

printf("size of union = %d bytes", sizeof(uJob));

printf("\nsize of structure = %d bytes", sizeof(sJob));

return 0;

Output

size of union = 32

size of structure = 40

Why this difference in the size of union and structure variables?

Here, the size of sJob is 40 bytes because

● the size of name[32] is 32 bytes

● the size of salary is 4 bytes

● the size of workerNo is 4 bytes

However, the size of uJob is 32 bytes. It's because the size of a union variable will always be the size
of its largest element. In the above example, the size of its largest element, (name[32]), is 32 bytes.

With a union, all members share the same memory.


43

Example: Accessing Union Members


#include <stdio.h>

union Job {

float salary;

int workerNo;

} j;

int main() {

j.salary = 12.3;

// when j.workerNo is assigned a value,

// j.salary will no longer hold 12.3

j.workerNo = 100;

printf("Salary = %.1f\n", j.salary);

printf("Number of workers = %d", j.workerNo);

return 0;

Output

Salary = 0.0

Number of workers = 100

C enums
In C programming, an enumeration type (also called enum) is a data type that consists of integral
44

constants. To define enums, the enum keyword is used.

enum flag {const1, const2, ..., constN};

By default, const1 is 0, const2 is 1 and so on. 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,

};

Or

Enumeration or Enum in C is a special kind of data type defined by the user. It consists of constant
integrals or integers that are given names by a user. The use of enum in C to name the integer values
makes the entire program easy to learn, understand, and maintain by the same or even different
programmer.

Syntax to Define Enum in C


An enum is defined by using the ‘enum’ keyword in C, and the use of a comma separates the
constants within. The basic syntax of defining an enum is:

enum enum_name{int_const1, int_const2, int_const3, …. int_constN};

In the above syntax, the default value of int_const1 is 0, int_const2 is 1, int_const3 is 2, and so on.
However, you can also change these default values while declaring the enum. Below is an example
of an enum named cars and how you can change the default values.

enum cars{BMW, Ferrari, Jeep, Mercedes-Benz};

Here, the default values for the constants are:


45

BMW=0, Ferrari=1, Jeep=2, and Mercedes-Benz=3. However, to change the default values, you can
define the enum as follows:

enum cars{

BMW=3,

Ferrari=5,

Jeep=0,

Mercedes-Benz=1

};

Enumerated Type Declaration to Create a Variable


Similar to pre-defined data types like int and char, you can also declare a variable for enum and other
user-defined data types. Here’s how to create a variable for enum.

enum condition (true, false); //declaring the enum

enum condition e; //creating a variable of type condition

Suppose we have declared an enum type named condition; we can create a variable for that data
type as mentioned above. We can also converge both the statements and write them as:

enum condition (true, false) e;

For the above statement, the default value for true will be 1, and that for false will be 0.

How to Create and Implement Enum in C Program


Now that we know how to define an enum and create variables for it, let’s look at some examples to
understand how to implement enum in C programs.

Also Read: Most Important Features of C Language You Must be Aware Of

Example 1: Printing the Values of Weekdays


#include <stdio.h>

enum days{Sunday=1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};


46

int main(){

// printing the values of weekdays

for(int i=Sunday;i<=Saturday;i++){

printf("%d, ",i);

return 0;

Output:

In the above code, we declared an enum named days consisting of the name of the weekdays
starting from Sunday. We then initialized the value of Sunday to be 1. This will assign the value for
the other days as the previous value plus 1. To iterate through the enum and print the values of each
day, we have created a for loop and initialized the value for i as Sunday.

Example 2: Assigning and Fetching Custom Values of Enum


Elements
#include<stdio.h>

enum containers{

cont1 = 5,

cont2 = 7,

cont3 = 3,

cont4 = 8

};

int main(){
47

// Initializing a variable to hold enums

enum containers cur_cont = cont2;

printf("Value of cont2 is = %d \n", cur_cont);

cur_cont = cont3;

printf("Value of cont3 is = %d \n", cur_cont);

cur_cont = cont1;

printf("Value of hearts is = %d \n", cur_cont);

return 0;

Output:

We have declared an enum named containers with four different containers as the elements in the
above code. We have then given custom values to the elements and initialized the variable for the
enum multiple times to print the relevant output.

How To Use Anum in C?


We use enums for constants, i.e., when we want a variable to have only a specific set of values. For
instance, for weekdays enum, there can be only seven values as there are only seven days in a week.
However, a variable can store only one value at a time. We can use enums in C for multiple purposes;
some of the uses of enums are:

● To store constant values (e.g., weekdays, months, directions, colors in a rainbow)

● For using flags in C

● While using switch-case statements in C


48

Example of Using Enum in Switch Case Statement


In this example, we will create an enum with all the 4 directions, North, East, West, and South as the
constants. We will then use the switch case statements to switch between the direction elements
and print the output based on the value of the variable for the enum directions.

#include <stdio.h>

enum directions{North=1, East, West, South};

int main(){

enum directions d;

d=West;

switch(d){

case North:

printf("We are headed towards North.");

break;

case East:

printf("We are headed towards East.");

break;

case West:

printf("We are headed towards West.");

break;

case South:

printf("We are headed towards South");

break;

return 0;

}
49

Output:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy