C++ constants



In C++, constants are values that do not change during the execution of a program. There are several ways to define constants in C++:


Using const keyword: You can use the const keyword to define a constant. The syntax is:


c++ code


const <data_type> <constant_name> = <value>;

const int PI = 3.14159; const string GREETING = "Hello, world!"; 


Using #define preprocessor directive: You can use the #define preprocessor directive to define a constant. The syntax is


#define <constant_name> <value


#define PI 3.14159 #define GREETING "Hello, world!" 


Using enum keyword: You can use the enum keyword to define a set of named constants. The syntax is:

enum <enum_name> { <constant1_name> = <value1>, <constant2_name> = <value2>, ... }; 

enum Color { RED = 0xFF0000, GREEN = 0x00FF00, BLUE = 0x0000FF }; 


In general, it is recommended to use the const keyword to define constants in C++. 

This is because const provides type safety and allows the compiler to perform optimizations that are not possible with #define or enum.