Literals in C++
In C++, literals are fixed values that are used directly in the code. They represent constant data. Here's a breakdown of the common types of literals in C++:
1. Integer Literals
- Represent whole numbers without any fractional part.
- Can be expressed in decimal (base 10), octal (base 8), or hexadecimal (base 16) forms.
- Decimal:
123,-45,0 - Octal:
012(starts with0),077 - Hexadecimal:
0x1A(starts with0x),0xFF
- Decimal:
- Can have suffixes to specify the integer type:
uorU: unsigned (e.g.,100u)lorL: long (e.g.,100l)llorLL: long long (e.g.,100ll)
2. Floating-Point Literals
- Represent numbers with a fractional part or an exponent.
- Can be expressed in decimal or exponential form.
- Decimal:
3.14,-0.001,12.0 - Exponential:
1.23e4(1.23 * 10^4),-0.5E-2(-0.5 * 10^-2)
- Decimal:
- By default, floating-point literals are of type
double. - Can have suffixes to specify the floating-point type:
forF: float (e.g.,3.14f)lorL: long double (e.g.,3.14l)
3. Character Literals
- Represent single characters enclosed in single quotes.
'A','z','5',' '(space)
- Can also represent special characters using escape sequences:
'\n': newline'\t': horizontal tab'\\'backslash'\'': single quote'\"': double quote
4. String Literals
- Represent sequences of characters enclosed in double quotes.
"Hello, world!","C++ programming"
- String literals are stored as null-terminated arrays of characters.
- Can contain escape sequences like character literals.
5. Boolean Literals
- Represent truth values.
- Two boolean literals:
truefalse
6. Pointer Literals
- Represent memory addresses.
- The only pointer literal is:
nullptr(represents a null pointer)
Example:
C++
#include <iostream>
int main() {
int age = 30; // 30 is an integer literal
double pi = 3.14159; // 3.14159 is a floating-point literal
char initial = 'J'; // 'J' is a character literal
std::string name = "John Doe"; // "John Doe" is a string literal
bool is_student = true; // true is a boolean literal
int* ptr = nullptr; // nullptr is a pointer literal
std::cout << "Age: " << age << std::endl;
std::cout << "Pi: " << pi << std::endl;
std::cout << "Initial: " << initial << std::endl;
std::cout << "Name: " << name << std::endl;
std::cout << "Is student: " << is_student << std::endl;
return 0;
}
In this example, 30, 3.14159, 'J', "John Doe", true, and nullptr are all literals. They represent fixed values that are used directly in the code.
Comments
Post a Comment