Literals in C++

Literals are fixed values that are directly specified in the source code. They are used to represent constant values that do not change during program execution.

Integer Literals

Integer literals represent whole numbers and can be specified in different number systems, such as decimal, octal, hexadecimal, and binary.

int decimal = 42;         // Decimal literal
int octal = 052;          // Octal literal (starts with 0)
int hexadecimal = 0x2A;   // Hexadecimal literal (starts with 0x)
int binary = 0b101010;    // Binary literal (starts with 0b)

Floating-Point Literals

Floating-point literals represent real numbers with fractional parts. They can be expressed in decimal or scientific notation.

float pi = 3.14159;           // Decimal notation
double scientific = 1.23e4;   // Scientific notation (1.23 x 10^4)

Character Literals

Character literals represent single characters and are enclosed in single quotes (' ').

char letter = 'A';        // Character literal
char newline = '\n';      // Special character literal (newline)

String Literals

String literals represent sequences of characters and are enclosed in double quotes (" ").

std::string message = "Hello, World!";   // String literal

Boolean Literals

Boolean literals represent the truth values of logical expressions and can have two values: true or false.

bool isTrue = true;       // Boolean literal (true)
bool isFalse = false;     // Boolean literal (false)

Null Pointer Literal

The null pointer literal represents a pointer that doesn't point to any memory location. It is represented by the value nullptr.

int* pointer = nullptr;   // Null pointer literal

User-Defined Literals

C++ allows you to define your own literals by overloading operators. User-defined literals can be used to create custom representations for specific types.

Summary

Literals in C++ are fixed values used to represent constants. They are available for different types, including integers, floating-point numbers, characters, strings, booleans, and pointers. Understanding the syntax and usage of literals is essential for writing concise and readable code.

Conclusion

In this tutorial, we explored the concept of literals in C++ programming. We covered various types of literals and provided examples to illustrate their usage. By understanding and utilizing literals effectively, you can enhance the clarity and expressiveness of your C++ code.