1. Literal Constants:
Literal constants are fixed values that appear directly in your code.
int num = 42; // Integer literal constant
double pi = 3.141592; // Floating-point literal constant
char ch = 'A'; // Character literal constant
2. Named Constants (const):
Named constants are created using the const
keyword. They provide a way to give a name to a constant value, making the code more readable and maintainable.
const int maxItems = 100;
3. Enumeration Constants (enum):
Enumeration constants are user-defined constants created using the enum
keyword. They represent a set of named integer values.
enum Color { Red, Green, Blue };
Color myColor = Green;
4. Constant Expressions:
You can create constant expressions using the constexpr
keyword. These are evaluated at compile-time.
constexpr int square(int x) {
return x * x;
}
int result = square(5); // Evaluated at compile-time
5. Preprocessor Macros (#define):
Preprocessor macros define constants using the #define
directive. These are replaced with their values during preprocessing.
#define PI 3.14159265
double circleArea = PI * radius;
6. User-Defined Literal Constants:
You can create your own user-defined literals in C++. This allows you to define custom constants with specific meanings and units.
constexpr long double operator"" _km(long double value) {
return value * 1000.0;
}
long double distance = 5.0_km; // Represents 5000.0
7. String Literals:
String literals, enclosed in double quotes, represent constant character arrays (C-strings).
const char* greeting = "Hello, World!";
8. Global Constants:
Constants declared outside of functions have global scope and can be accessed throughout the program.
const int GLOBAL_CONSTANT = 100;
Remember that C++ provides various types of constants to suit different needs. The use of named constants (const
and enum
) is generally encouraged to improve code readability and maintainability. Additionally, constexpr
and user-defined literals are powerful features in C++ for creating compile-time constants and custom units of measurement, respectively.