×

C - CONSTANTS


In this chapter will understand constant or literals.


What is Constant in C ?

A constant is any data that can be assigned as a value to a variable. For example, 5, 24.02, true, false, etc.

Unlike variables, constant refers to fixed values that the program may not change during the execution of the program. Constant can be of any data type such as integer, float, char, string etc.

Constant are also referred as literals.

Let's study different literals available in C.

Integer literals

In C, an integer literal can be of decimal, octal or hexadecimal value. To determine the type of integer literals, C specify prefix as

  • Nothing for decimal

  • 0 for octal

  • 0X or 0x for hexadecimal

Integer literal example -
 022 // octal literal
 0xABC // hexadecimal literal
 24 // decimal literal

Floating-point literal

The floating point literal have 4 parts namely, integer part, decimal part, fractional part and exponent part.

The floating point literal can be represent in two ways, one is decimal representation and the other is exponent representation.

1. Decimal representation -

To represent in this form, we must include a decimal point, exponent or both of them. For example -

 3.14159 //value of pi 

2. Exponent representation

To represent in this form, we must include integer part, fractional part or both. Symbol e or E is used to represent exponent. For example -

 314159E-5L //value of pi

Character constant

A character constant is any character enclosed in single quotation marks. For example - 'x', '7', 'Z' etc.

Escape sequence

There are some character that can not be typed such as tab, space and enter etc, to use those characters escape sequence is used. The backslash(\) is used to tell the compiler that it is escape character. For example, \n is a new line character and \t is a tab character etc.

String constant

String constants in c are constants that are enclosed in double quotes "". For example -

We will study all of these in general with seperate chapters with relavent examples. We will study these in C programming language.

 "Hello world"
 " "
 "C"
 "Welcome \n to Earth coding."

Enumeration constant

In c, enum keyword is used to define enumeration types. For example -

 enum brands {Google, apple, Samsung, Mi }; 

Here brands is a variable and Google, apple, Samsung and Mi are the constants having the value 0, 1, 2 and 3 respectively.


How to define Constants

In C we can define constant in two ways,

Using the #define preprocessor and

Using the const keyword

#define

The syntax to define a constant using #define is as follows

Syntax
 #define identifier value 
Example
 #define PI 3.14159 

const keyword

The syntax to define constant with const keyword is as follows

Syntax
 const data_type variable = value; 
Example
 const float PI = 3.14159; 

Normally it is considered a good practice to define constants in CAPITALS.

In the next chapter, We will learn about Keywords and identifiers.