Literals in C++
A literal in C++ is a fixed value that is shown explicitly in the source code. Within a program, these values are utilized in expressions or to initialize variables. Integers, floating-point numbers, characters, and other data types can all be represented by literals. Multiple literal types are supported by C++, each of which is intended to represent a particular type of data.
- Integer Literals:
Whole numbers are represented by integer literals, which can be expressed in a variety of bases, including hexadecimal, octal, and decimal.
Syntax:
It has the following syntax:
int decimalLiteral = 412; // Decimal
int octalLiteral = 0521; // Octal (starts with 0)
int hexadecimalLiteral = 0x2A; // Hexadecimal (starts with 0x)
Example:
// C++ Proram to illustrate the use of integer literals
#include <iostream>
using namespace std;
int main()
{
int marks = 25; // An integer literal
cout << "marks: " << marks << endl;
return 0;
}
Output:
marks: 25
- Floating Point Literals:
The floating-point literals represent the numbers with a fractional component. Scientific or standard notation can be used to write them.
Syntax:
It has the following syntax:
float floatLiteral = 3.14f; // Standard notation
double doubleLiteral = 6.022e23; // Scientific notation
Example:
Let us take an example to illustrate the floating point literals in C++.
#include <iostream>
using namespace std;
int main()
{
// float literal
float e = 2.7f;
// double literal
double pi = 3.14;
// long double literal
long double g = 9.8L;
cout << "The Value of pi: " << pi << endl;
cout << "The value of e: " << e << endl;
cout << "The value of g: " << g << endl;
return 0;
}
Output:
The Value of pi: 3.14
The value of e: 2.7
The value of g: 9.8
- Character Literals:
Single quotes surround literal characters. A wide character literal (such as L'x') should be stored in a variable of the wchar_t type if the literal starts with L (uppercase only). Otherwise, it is a literal narrow character (like "x") that can be kept in a basic char variable.
Character literals can be any of the following: 'x', an escape sequence, '\t', or '\u02C0', which is an example of a universal character.
A backslash before some characters in C++ indicates that they have a specific meaning and are used to indicate things like newline (\n) or tab (\t).
Syntax:
It has the following syntax:
char charLiteral = 'H';
Example:
// C++ program to illustrate the use of charater literal
#include <iostream>
using namespace std;
int main()
{
char grade = 'A';
cout << "Grade: " << grade << endl;
return 0;
}
Output:
Grade: A
- Boolean Literals:
It represents either true or false.
bool trueLiteral = true;
bool falseLiteral = false;
- String Literals:
Double quotes are used to enclose string literals. Characters like escape sequences, universal characters, and plain characters can all be found in strings. Using string literals, you can divide a lengthy line into multiple lines and use whitespaces to separate them.
Syntax:
It has the following syntax:
"hello, dear"
"hello, \
dear"
"hello, " "d" "ear"
const char* stringLiteral = "Hello, World!";
Example:
#include <iostream>
using namespace std;
int main()
{
const char* message = "Hello, Tutorial and example!";
cout << "Message: " << message << endl;
return 0;
}
Output:
Message: Hello, Tutorial and example!
- Null Pointer Literals:
It is frequently utilized in pointers. The null pointer literal is a representation of a null pointer.
Syntax:
It has the following syntax:
int* nullPointer = nullptr;
Example:
Let us take an example to illustrate the literals in C++.
#include <iostream>
int main() {
// Integer Literals
int decimalLiteral = 42;
int octalLiteral = 052;
int hexadecimalLiteral = 0x2A;
// Floating-Point Literals
float floatLiteral = 3.14f;
double doubleLiteral = 6.022e23;
// Character Literals
char charLiteral = 'A';
// String Literals
const char* stringLiteral = "Hello, World!";
// Boolean Literals
bool trueLiteral = true;
bool falseLiteral = false;
// Null Pointer Literal
int* nullPointer = nullptr;
// Outputting values
std::cout << "Integer Literals:" << std::endl;
std::cout << "Decimal: " << decimalLiteral << std::endl;
std::cout << "Octal: " << octalLiteral << std::endl;
std::cout << "Hexadecimal: " << hexadecimalLiteral << std::endl;
std::cout << "\nFloating-Point Literals:" << std::endl;
std::cout << "Float: " << floatLiteral << std::endl;
std::cout << "Double: " << doubleLiteral << std::endl;
std::cout << "\nCharacter Literal:" << std::endl;
std::cout << "Char: " << charLiteral << std::endl;
std::cout << "\nString Literal:" << std::endl;
std::cout << "String: " << stringLiteral << std::endl;
std::cout << "\nBoolean Literals:" << std::endl;
std::cout << "True: " << trueLiteral << std::endl;
std::cout << "False: " << falseLiteral << std::endl;
std::cout << "\nNull Pointer Literal:" << std::endl;
std::cout << "Null Pointer: " << nullPointer << std::endl;
return 0;
}
Output:
Integer Literals:
Decimal: 42
Octal: 42
Hexadecimal: 42
Floating-Point Literals:
Float: 3.14
Double: 6.022e+23
Character Literal:
Char: A
String Literal:
String: Hello, World!
Boolean Literals:
True: 1
False: 0
Null Pointer Literal:
Null Pointer: 0
Example 2:
Let us take an example to illustrate the literals in C++.
#include <iostream>
int main() {
// Integer Literals
int a = 10;
int b = 4;
// Arithmetic Expressions with Integer Literals
int sum = a + b;
int difference = a - b;
int product = a * b;
int quotient = a / b;
// Floating-Point Literals
double pi = 3.14159;
// Circle Calculation using Floating-Point Literals
double radius = 5.0;
double area = pi * radius * radius;
double circumference = 2 * pi * radius;
// Character Literals
char firstInitial = 'J';
char lastInitial = 'D';
// String Concatenation
std::string fullName = "John" + std::string(1, firstInitial) + "oe" + " " +
"D" + lastInitial + "e";
// Boolean Literals
bool isCplusplusFun = true;
bool isJavaFun = false;
// Logical Expressions with Boolean Literals
bool bothAreFun = isCplusplusFun && isJavaFun;
bool eitherIsFun = isCplusplusFun || isJavaFun;
bool notJavaFun = !isJavaFun;
// Outputting Results
std::cout << "Arithmetic Expressions:" << std::endl;
std::cout << "Sum: " << sum << std::endl;
std::cout << "Difference: " << difference << std::endl;
std::cout << "Product: " << product << std::endl;
std::cout << "Quotient: " << quotient << std::endl;
std::cout << "\nCircle Calculation:" << std::endl;
std::cout << "Area: " << area << std::endl;
std::cout << "Circumference: " << circumference << std::endl;
std::cout << "\nString Concatenation:" << std::endl;
std::cout << "Full Name: " << fullName << std::endl;
std::cout << "\nLogical Expressions:" << std::endl;
std::cout << "Both Are Fun: " << bothAreFun << std::endl;
std::cout << "Either Is Fun: " << eitherIsFun << std::endl;
std::cout << "Not Java Fun: " << notJavaFun << std::endl;
return 0;
}
Output:
Arithmetic Expressions:
Sum: 14
Difference: 6
Product: 40
Quotient: 2
Circle Calculation:
Area: 78.5397
Circumference: 31.4159
String Concatenation:
Full Name: JohnJoe DDe
Logical Expressions:
Both Are Fun: 0
Either Is Fun: 1
Not Java Fun: 1
Example 3:
#include <iostream>
int main() {
// Integer Array with Integer Literals
int numbers[] = {1, 2, 3, 4, 5};
// Loop to Access and Display Array Elements
std::cout << "Array Elements:" << std::endl;
for (int i = 0; i < 5; ++i) {
std::cout << numbers[i] << " ";
}
std::cout << std::endl;
// Floating-Point Literals in Conditional Statement
double temperature = 25.5;
if (temperature > 30.0) {
std::cout << "It's a hot day!" << std::endl;
} else {
std::cout << "It's a moderate day." << std::endl;
}
// Character Literals in Switch Statement
char grade = 'B';
switch (grade) {
case 'A':
std::cout << "Excellent!" << std::endl;
break;
case 'B':
std::cout << "Good job!" << std::endl;
break;
case 'C':
std::cout << "Satisfactory." << std::endl;
break;
default:
std::cout << "Need improvement." << std::endl;
}
// Boolean Literals in Loop Condition
bool keepLooping = true;
int counter = 0;
while (keepLooping) {
std::cout << "Loop iteration " << counter << std::endl;
++counter;
if (counter >= 3) {
keepLooping = false;
}
}
// String Literal in Function
std::string greet = "Hello, ";
std::string name = "Alice";
std::cout << greet + name + "!" << std::endl;
return 0;
}
Output:
Array Elements:
1 2 3 4 5
It's a moderate day.
Good job!
Loop iteration 0
Loop iteration 1
Loop iteration 2
Hello, Alice!
Example 4:
#include <iostream>
#include <string>
int main() {
// String Literal for a Menu
std::cout << "Select an option:" << std::endl;
std::cout << "1. Display information\n2. Enter your name\n3. Exit" << std::endl;
// Integer Literal for User Input
int userChoice;
std::cout << "Enter your choice (1-3): ";
std::cin >> userChoice;
// Conditional Statements Based on User Input
if (userChoice == 1) {
std::cout << "Information: C++ literals represent fixed values in the code." << std::endl;
} else if (userChoice == 2) {
// String Literals for User Interaction
std::string userName;
std::cout << "Enter your name: ";
std::cin.ignore(); // Ignore newline character from previous input
std::getline(std::cin, userName);
std::cout << "Hello, " << userName << "!" << std::endl;
} else if (userChoice == 3) {
std::cout << "Exiting the program. Goodbye!" << std::endl;
} else {
std::cout << "Invalid choice. Please enter a number between 1 and 3." << std::endl;
}
return 0;
}
Output:
Select an option:
1. Display information
2. Enter your name
3. Exit
Enter your choice (1-3): 2
Enter your name: HARSHAVARDHAN
Hello, HARSHAVARDHAN!
Conclusion:
Literals in C++ play a fundamental role in programming by directly representing fixed values in the source code. Several types of values are possible for these: characters, strings, booleans, integers, and floating-point numbers. Literals are used in many C++ programs for arithmetic operations, variable initialization, logical decision-making, and input/output user interaction. Literals are extremely flexible and can be used in a wide range of scenarios, such as conditional statements, user input processing, array initialization, and loop conditions. The utilization of them enhances the readability and conciseness of the code by increasing its clarity.