Table of Contents
Literals In C/C++ With Examples
Literals in the C and C++ programming languages are fundamental building blocks that represent constant values directly in code. These constants can include integers, floating-point numbers, characters, and more. Literals are essential for initializing variables, specifying values in expressions, and conveying data directly within the source code. They provide a means to express concrete values without requiring variables or complex computations. In this exploration of literals in C/C++, we will delve into the various types of literals and provide illustrative examples to demonstrate their usage and significance in these programming languages.
Literals In C/C++
Literals in programming, whether in C or C++, are indeed constant values assigned to variables that remain fixed and unmodifiable throughout the program’s execution. Unlike variables, literals are not associated with references and directly hold their values in memory. In common usage, the terms “constants” and “literals” are often used interchangeably.
For instance, consider the expression “const int x = 5;,” where the value 5 is a constant integer literal. In the world of C, there are four primary types of literals, while in C++, there are five:
- Integer Literal: Used to represent whole numbers, such as
42
. - Float Literal: Represents decimal numbers with a fractional part, like
3.14
. - Character Literal: Represents a single character enclosed in single quotes, such as
'A'
. - String Literal: Represents a sequence of characters enclosed in double quotes, like
"Hello, World!"
. - Boolean Literal (C++): Represents either
true
orfalse
, indicating logical values in C++.
These literals play a pivotal role in coding by providing a concise way to embed fixed values directly into the source code, enhancing readability and maintainability.
1.Integer Literals
Integer literals serve as a means to represent and store integer values in programming. They can be expressed in two primary types:
A) Prefixes: The use of prefixes with integer literals indicates the base or radix in which the literal is to be interpreted or read. These prefixes provide information about the numeric base of the integer value, which can be essential when working with numbers in different bases.
Example
0x10 = 16
Because 0x prefix represents a HexaDecimal base. So 10 in HexaDecimal is 16 in Decimal. Hence the value 16.
Integer Literals are of 2 types:
a. Decimal-literal(base 10)
It consists of a non-zero decimal digit followed by zero or more decimal digits, where decimal digits include the numbers 0 through 9. This is the common representation for integers in these programming languages, allowing you to express a wide range of positive integer values.
Example:
56, 78
b. Octal-literal(base 8):
It begins with a ‘0’ (zero) followed by zero or more octal digits, where octal digits include the numbers 0 through 7. This representation allows you to specify integer values in octal base, which is base 8. Octal literals are less commonly used than decimal literals but can be useful in certain situations, especially when dealing with permissions and bit manipulation.
Example:
045, 076, 06210
d. Binary-literal(base 2)
It starts with either ‘0b’ or ‘0B’ followed by one or more binary digits, which are 0 and 1. This notation is used to represent integer values in binary base, which is base 2. Binary literals are valuable for expressing binary-encoded data or when working with low-level bit manipulation operations.
Example
0b101, 0B111
B) Suffix
Suffixes are added to the literal to specify its data type
Example
12345678901234LL
indicates a long long integer value 12345678901234 because of the suffix LL
These are represented in many ways according to their data types.
- int: No suffix is required, as an integer constant is assigned as an
int
by default. - unsigned int: Append ‘u’ or ‘U’ at the end of an integer constant.
- long int: Add ‘l’ or ‘L’ at the end of an integer constant.
- unsigned long int: Include ‘ul’ or ‘UL’ at the end of an integer constant.
- long long int: Use ‘ll’ or ‘LL’ as a suffix for an integer constant.
- unsigned long long int: Employ ‘ull’ or ‘ULL’ as a suffix for an integer constant.
Example
#include <stdio.h>
int main()
{
// constant integer literal
const int intVal = 10;
printf("Integer Literal:%d \n", intVal);
return 0;
}
Output
Integer Literal:10
2) Floating-Point Literals
Floating-point literals are used to represent and store real numbers, which consist of an integer part, real part, fractional part, and exponential part. These literals can be represented in either decimal form or exponential form.
When creating floating-point literals, it’s essential to adhere to certain rules:
- Decimal Form: If representing a floating-point number in decimal form, it should include the decimal point, exponent part, or both. Failing to include these components may result in an error.
- Exponential Form: When using exponential form, ensure that it includes the integer part, fractional part, or both, as required. Omitting any of these parts can lead to an error.
Adhering to these guidelines helps maintain the accuracy and validity of floating-point literals, preventing potential errors in the code.
Floating-point literal representations are shown below:
Valid Floating Literals:
10.125
1.215-10L
10.5E-3
Invalid Floating Literals:
123E
1250f
0.e879
Example
#include <iostream>
using namespace std;
int main()
{
// Real literal
const float floatVal = 4.14;
cout << "Floating-point literal: "
<< floatVal << "\n";
return 0;
}
Output
Floating point literal: 4.14
3) Character Literal
Character literals are used to store a single character enclosed within single quotes (”). To store multiple characters, you would typically use a character array. Attempting to store more than one character within single quotes results in a warning, and only the last character of the literal is considered.
There are two primary representations of character literals:
A. char Type: This representation is used to store normal character literals or narrow-character literals. It is supported by both C and C++. Character literals of this type can hold a single character within single quotes and are widely used in both languages.
Example:
// For C
char chr = 'G';
// For C++
char chr = 'G';
B. wchar_t type: Unlike the ‘char’ type, ‘wchar_t’ is used to represent wide-character literals and is supported only in C++. When a character is followed by the ‘L’ prefix, it indicates that the literal should be stored as a ‘wchar_t,’ representing a wide-character literal. This is particularly useful for dealing with wide characters and character sets that require a larger storage space than regular narrow characters.
// Not Supported For C
// For C++
wchar_t chr = L'G';
Example:
#include <stdio.h>
int main()
{
// constant char literal
const char charVal = 'A';
printf("Character Literal: %c\n",
charVal);
return 0;
}
Output :
Character Literal: A
4) String Literals
String literals indeed serve as containers for multiple characters and are enclosed within double quotes (“”). Unlike character literals, string literals can store sequences of characters, making them suitable for representing text and longer data.
String literals can also handle special characters and escape sequences, which are denoted by backslashes, such as ‘\n’ for a newline or ‘\t’ for a tab. This flexibility allows you to include various characters and control codes within a string.
char greeting[] = "Hello, World!";
Example
#include <stdio.h>
int main() {
// String literal
char greeting[] = "Hello, World!";
// Printing the string literal
printf("Message: %s\n", greeting);
return 0;
}
Output
Hello, World!
5) Boolean Literals
.Boolean literals are specific to C++ and are used to represent boolean data types. These literals can have two values:
- true: This represents the “True” value and should not be considered equal to the integer 1, as it’s a distinct boolean value.
- false: This represents the “False” value and should not be considered equal to the integer 0, as it’s a distinct boolean value.
Boolean literals are essential for writing clear and unambiguous code in C++ when working with boolean data types, making the code more expressive and readable.
// C++ program to show Boolean literals
#include <iostream>
using namespace std;
int main()
{
const bool isTrue = true;
const bool isFalse = false;
cout << "isTrue? "
<< isTrue << "\n";
cout << "isFalse? "
<< isFalse << "\n";
return 0;
}
Output
isTrue? 1
isFalse? 0
FAQ- Literals In C/C++ With Examples
Q1. What is literals with example?
Ans. Literals are indeed constant values that are directly embedded in a program’s code and can be assigned to variables. Your example, “int count = 0;”, demonstrates this concept effectively.
In this statement, “int count” is the declaration of an integer variable named ‘count,’ and the literal ‘0’ directly represents the value assigned to this variable, which, in this case, is zero. Literals are a fundamental part of programming, helping to initialize variables and express fixed values within the code.
Q2. How are literals stored in c?
Ans.String literals are indeed stored in the program’s memory as a sequence of characters, and they are terminated by a null character (‘\0’) with an ASCII value of 0. This null character marks the end of the string, allowing functions that operate on strings to determine where the string ends.
Q3. Which are examples of numeric literals?
Ans.Examples for Numeric literals are 1 , . 2 , 3.4 , -5 , -6.78 , +9.10 . Approximate-value numeric literals are represented in scientific notation with a mantissa and exponent.
Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together