Literals And Escape Sequence In C++
Posted on December 4, 2023 by Vishesh Namdev
Python
C
C++
Javascript
Java
Literal is a notation for representing a fixed value in source code. Literals can be used to express constants of various types, such as integers, floating-point numbers, characters, and strings. C++ supports several types of literals, and each type has its own syntax.
Here are some common types of literals in C++:
1. Integer Literals:
int
decimalLiteral
=
42
;
int octalLiteral = 052 ; // Octal (prefix 0)
int hexadecimalLiteral = 0x2A ; // Hexadecimal (prefix 0x or 0X)
int octalLiteral = 052 ; // Octal (prefix 0)
int hexadecimalLiteral = 0x2A ; // Hexadecimal (prefix 0x or 0X)
2. Floating-point Literals:
double
standardFloatLiteral
=
3.14
;
double scientificFloatLiteral = 2.0e5 ; // 2.0 * 10^5
double scientificFloatLiteral = 2.0e5 ; // 2.0 * 10^5
3. Character Literals:
char
singleCharLiteral
= '
A
';
char escapeCharLiteral = ' '; // Newline character
char escapeCharLiteral = ' '; // Newline character
4. String Literals:
const
* stringLiteral
= "
Hello, World!
";
5. Boolean Literals:
bool
trueLiteral
=
true
;
bool trufalseLiteraleLiteral = false ;
bool trufalseLiteraleLiteral = false ;
Escape Sequence
Escape sequence is a special combination of characters that starts with a backslash and is used to represent special characters or actions within strings. For example, represents a newline, represents a tab, "" represents a double quote, and so on. Escape sequences make it easier to include certain characters in strings.
Example of Escape Sequence:-
#include
<iostream>
int main () {
std::cout << " Hello, World! This is a new line. ";
std::cout << " This is tab separated. ";
std::cout << " This is a backslash: \ and this is a quote: "" ";
return 0 ;
}
int main () {
std::cout << " Hello, World! This is a new line. ";
std::cout << " This is tab separated. ";
std::cout << " This is a backslash: \ and this is a quote: "" ";
return 0 ;
}