Broad Network


Type Qualifiers in the C Computer Language

Part 36 of the Complete C Course

Foreword: Type Qualifiers in the C Computer Language

By: Chrysanthus Date Published: 22 Jun 2024

Introduction

Type qualifiers are: const, restrict, volatile, and _Atomic. Only const with respect to pointers, is explained in this section of the chapter.

const and Pointers
Consider the following code segment:

            int  pointed = 5;
            int * pointer = &pointed;

This is the normal way to create a pointer to a pointed object. To make the pointed object constant, modify the first statement as follows:

            const int  pointed = 5;

To make the pointer constant, modify the second statement as follows:

            int * const pointer = &pointed;

A constant pointer means that the pointer cannot be given any other address. In other words, the pointer cannot hold any new address, down in the program. To make both pointed object and pointer object constant, modify both statements as follows:

            const int pointed = 5;
            int * const pointer = &pointed;

The compiler may issue a warning message, but ignore it. This code segment makes the value of the variable, pointed, un-modifiable using pointed, and also makes the value (address) of the variable, pointer, un-modifiable using pointer. Under this condition, the value for the variable, pointed, can still be modified using *pointer, as the following code segment depicts:

            const int pointed = 5;
            int * const pointer = &pointed;
            *pointer = 6;
            printf("%i\n", *pointer);

The output is 6, and not 5. The value for the variable, pointed, has been modified using the variable pointer. To prevent the variable, pointed, from being modified by the variable, pointer, change the second statement of the code segment, as in the following code:

            const int pointed = 5;
            const int * const pointer = &pointed;
            // *pointer = 6;
            printf("%i\n", *pointer);

The new second statement is the old second statement preceded by const. If the comment symbol is removed, the code segment will not compile; and an error message will be issued.



The first part of this C course begins at (click): Installing gcc and Running Your First C Program

The Second part of this C course begins at (click): Enumeration in the C Computer Language

After completing this C course, do some practices while learning the minimum algorithms required for a C Algorithm developer, in big tech companies. Click:
Explanations in C for the 17 Algorithm Lessons at https://app.codility.com/programmers with Problems and Solutions

Related Links

More Related Links

Cousins

BACK NEXT

Comments