Literals in C Language

Introduction

In the C programming language, literals are fixed values that are directly represented in the source code. They are constant values that are used to assign values to variables or used in expressions without any computation. In this tutorial, we will explore literals in C, discuss the different types of literals, and provide descriptions with examples for each type.

Types of Literals in C

Literal TypeDescriptionExample
Integer LiteralsWhole numbers without a fractional part42, -10, 0
Floating-Point LiteralsReal numbers with a fractional part3.14, -0.5
Character LiteralsIndividual characters enclosed in single quotes'A', '7', '\n'
String LiteralsSequence of characters enclosed in double quotes"Hello, World!", "C"
Boolean LiteralsRepresent truth values (true or false)1 (true), 0 (false)
Null LiteralRepresents absence of a value or null pointerNULL

Integer Literals

Integer literals represent whole numbers without a fractional part. They can be written in decimal, octal, or hexadecimal formats. Examples include 42, -10, 0, 025 (octal), and 0x1A (hexadecimal).

Floating-Point Literals

Floating-point literals represent real numbers with a fractional part. They can be written in decimal or exponential notation. Examples include 3.14, -0.5, 2.5e-3, and -1.23E+4.

Character Literals

Character literals represent individual characters enclosed in single quotes (''). They can be alphabets, digits, special characters, or escape sequences. Examples include 'A', '7', '$', '\n', and '\t'.

String Literals

String literals represent a sequence of characters enclosed in double quotes (""). They can be a combination of alphabets, digits, and special characters. Examples include "Hello, World!", "C Programming", and "12345".

Boolean Literals

Boolean literals represent truth values, either true or false. In C, true is represented by the value 1, and false is represented by the value 0.

Null Literal

The null literal represents the absence of a value or a null pointer. In C, the null literal is represented by the keyword NULL.

Example

In the above example, we declare variables and assign them different types of literals. The age variable is assigned an integer literal, pi is assigned a floating-point literal, grade is assigned a character literal, name is assigned a string literal, isStudent is assigned a boolean literal, and ptr is assigned a null literal. We use printf() to display the values of these variables.

Output:

By utilizing literals in C, you can assign constant values directly in your code, making it more readable and efficient.