Constants in C

Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!

Learn via video course

C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
By Prateek Narang
Free
star5
Enrolled: 1000
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
Prateek Narang
Free
5
icon_usercirclecheck-01Enrolled: 1000
Start Learning

Constants in C

Overview

Variables having fixed values that don’t change and cannot be changed throughout the execution of the program once initialized are called Constants.

There are mainly two types of constants: primary and secondary. Primary and secondary constants are once again divided into subcategories. Constants in C can be declared in two ways, viz. Use the const keyword or the #define preprocessor directive.

Scope

  • In this article, we will understand what constants are and how to declare a constant.
  • This article explains different types of constants.
  • This article doesn’t explain each datatype in detail.

Introduction

Variables and Constants in C

In our everyday life, we have encountered many constants such as pi, gravitational constant, acceleration due to gravity, etc. We know that the values of constants are fixed and cannot be changed. But computers, by default don’t know what constants are, and while coding we will tell the computer which variable should be stored as constants. In this article, let us look at the different types of constants and how we can declare a variable as a constant.

There might be some data whose values remain constant throughout the program execution. Such variables are known as Constant Variables. The values assigned to the variables are known as the literal.

Assign value to constant

In the above illustration, we can see that we have created a constant x and assigned a value of 5 to the constant. Here the value assigned to the constant is known as the literal.

This article will learn about the const int x part in detail. So, no need to worry if you didn’t understand.

What are Constants in C?

As the name suggests, Constants are the variables whose values cannot be changed throughout the execution of the program once they are initialized at the beginning of the program. Constants are also known as literals. A number, a character, a string of characters, an array, a structure, a union, a pointer, and an enum can be set as a constant.

How to Use Constants in C?

In the C programming language, A variable can be used as a constant by the following methods:

  • Using const keyword.
  • Using the #define preprocessor.

Before we start creating the constants, Let us have an insight into the different kinds of Constants in C.

Types of Constants in C

Constants can be broadly divided into two types:

  • Primary Constants
  • Secondary Constants

Again the primary and secondary constants are divided, which can be seen in the hierarchy illustrated below.

Types of Constants in C

Primary Constants

Constants of type float, integer, and character are known as Primary constants.

Example for Primary constants:
1, 1.23, "Scaler", 'h', etc.

As you can see that float, integer, and character are primary constants and we know that float, integer, and character are primary data types. As the constants are of primary data type, they are known as primary constants.

Primary constants can be once again divided into

  • Numeric Constants
  • Character Constants

Numeric Constants

Numeric constants contain signed or unsigned numerals, or a zero or a decimal. In a nutshell, all types of numbers come under Numeric constants.

Numeric constants are once again divided into three types:

  • Decimal Integer
  • Octal Integer
  • Hexadecimal Integer

Integer Constants
Integer constants are the numbers with decimals (base 10), hexadecimal (base 16), binary (base 2), or octal (base 8). We will understand this better once we look into each of the Integer constants.

Let us know more about each integer constant in detail.

Decimal Integer
Decimal integers are the constants with base 10. Non-zero decimal digits (1 to 9) are decimal integers followed by zero or more decimal digits (0 to 9 ).

Example: 255,100,69,999, etc.

Octal Integer
Octal integers are the constants with base 8. The digit zero (0) is followed by zero or more octal digits (0 to 7).

Example:0, 0125, 034673, 03245, etc.

Hexadecimal Integer
Hexadecimal integers are the constants with base 16. The sequence starts with 0x followed by one or more hexadecimal digits (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, A, b, B, c, C, d, D, e, E, f, F).

Example:0x3b24, 0XF96, 0x21, 0x3AA, 0X29b, 0X4bD, etc.

Real Constants
A constant with the combination of positive, negative, or zero followed by a decimal point and the fractional part is known as a real constant.

Example:-89, 0.123, 45, etc.

Character Constants

One or more characters are enclosed within a single quote (' ') or ("") depending on the type of characters.

Single Character Constants
Character constants having a single character enclosed within the ' ' (Single quote) are known as character constants.
Example: 's', 'c', 'a', 'l', 'e', 'r', etc.

String Constants
Character constants with various special symbols, digits, characters, and escape sequences enclosed within the " "(double quotes) are known as string constants.

Let us look at the examples and try to understand them better.
Example: "Scaler", "by", "InterviewBit", "123", "number1" etc.

As we can see in the above examples, all the words or the strings are enclosed within the double-quotes. If we look at the last two examples, we can see numbers, but the numbers are treated as strings by the computer because they are enclosed inside the double quotes.

Backslash Character Constants

Backslash characters or escape sequences are the types of character constants. A definite backslash character performs a specific task. Let’s imagine that we are writing a code, and in the code, we added a couple of sentences, and we want them to be printed in separate lines. For this purpose, we can write the printf statement thrice, but it is not an efficient way to write the code. Now we have to tell the compiler to print the sentences in 3 different lines and how can we tell it to the compiler? We can use the backslash character \n to tell the compiler to print the sentences in 3 different lines. Here is a list of backslash characters and their meaning:

ConstantsMeaning
\abeep sound
\bbackspace
\fform feed
\nnew line
\rcarriage return
\thorizontal tab
\vvertical tab
\'single quote
\"double quote
\\backslash
\0null

Secondary Constant

The datatypes such as Array, Pointers, Structure, Union, and Enum having a constant fixed value that remains the same during the entire execution of the program are known as secondary constants.
We can see that these are secondary data types and we can conclude that the secondary data types are considered Secondary data types.

Types of Secondary Constant

There are mainly five types of secondary constants. Let us briefly look at each of the secondary constants in detail.

  • Arrray
    A collection of similar data items stored at contiguous memory locations is called an Array. An array can be imagined as an egg tray, where eggs are placed in the tray. Similarly, the array is like the egg tray, and the data stored in the array can be imagined as the egg placed in the tray.
    Example: int marks[100], float numbers[50], char name[50], etc.

When the elements stored in an array are made constant, the array is said to be a constant array.

  • Pointer
    Pointers are the special kind of variables that holds the address of other variables rather than the values. Example: int* p, int* pointer, etc.
    When a pointer holds the address of the same variable throughout the execution of the program, then it is known as a constant pointer.

  • Structure
    Structures are user-defined datatypes that can be used to group different data types into a single datatype. The structure is a group of different data types grouped. Suppose that we want to store the details of a person, such as a name, gender, phone number, and age. We can create a separate variable for each particular and store the value. Imagine if you want to store the details of 100 employees in a company, It would be cumbersome to store the value of 4 particulars of each employee, which is 400 different variables. Instead, we can create a single structure and use the same structure 100 times.

Example

When the contents of the structure remain the same throughout the execution of the program, then it is known as a constant structure.

  • Union
    Union is a data type in C that allows us to store different data types in the same location. We can define a union with many members but the union can contain a value at a given time.

Example:

  • Enum
    Enum or an Enumerated type is a user-defined datatype which is used to assign names to integral constants because names are easier to handle in a program.

    Example: enum vehicle{car, bus, train, bike};

    Here, the car will have the value of 0, the bus will have the value of 1 and so on. We will understand Enum in a better way in our other articles and let's concentrate on Constants in C in this article.

Ways to Define Constants in C

So far, we have learnt what constants are and what are the different types of constants. Now let us see how to create a constant and what happens if we try to change the value of a constant. We can define a constant mainly in two different ways. They are:

const Keyword

Using the const keyword is the most basic and simplest way to declare a constant. You just have to add a const keyword preceding the declaration of the variable. While using the const keyword to define a constant one should keep in mind that the constant has to be initialized at the beginning of the program and cannot be changed later.

The following example explains how to declare a variable as constant:

As we can see that in the above program, we are trying to find the area of a circle. As we know that the value of pi is constant, and its value is approximately equal to 3.14. We will ask the user to enter the value of the radius, and we will calculate the area of the circle using the formula KaTeX parse error: $ within math mode, and we will print the area of the circle. Here we made use of the value of pi which was declared as constant at the beginning of the code.

The output of the above code is as follows:

#define Preprocessor Directive

As we have seen in the previous instance that while using the const keyword, we should follow the syntax of const datatype variable-name =value;. Suppose in our code we have created a structure and we need to use the structure for many instances in the program, Then it is cumbersome to use the big const keyword again and again in our program. Therefore we make use of the #define preprocessor to create an alias name for the existing variable.

#define preprocessor directive in the C language comes under the topic of macros definition. In this article, we shall discuss how to use the #define preprocessor directive and we shall discuss the macro's definition in other articles.

While using the #define preprocess, we have to keep in mind a few things.

  • The constant should be declared before the main function.
  • The common mistakes committed during the initialization of constant using #define preprocessor is adding a semicolon at the end of the declaration. Semicolons should not be added at the end of the declaration of a constant using the #define preprocessor.

Let us look at the syntax to define a constant using the #define keyword.

#define constant_name value

Let us look at an example to understand how to create a constant using the #define:

In the above code, We are trying to calculate the area of a circle similar to how we did in the previous example but this time we will be using the #define preprocessor directive. The output of the above code is as follows:

So far we have seen what constants are, the types of constants, and how to declare a constant. You would be curious to know what happens if we try to change the value of a constant. Let us try to change the value of the constant in the below program.

The output of the above code is as follows:

As we can see that the compiler shows an error saying that the value of a is read-only.

Conclusion

  • The variables whose value cannot be changed throughout the execution of the program are known as constants.
  • Constants are used when programs involving constants are required.
  • Constants of primary variables are known as primary constants, and constants of secondary variables are known as Secondary constants.
  • A variable can be set as constant using the const keyword or using the #define preprocessor.