Constants / Literals in C++Constants refer to fixed values that the program may not alter. They are also called literals. Declaration of constantsYou can directly use constant values in statements, such as: b = a + 20; // 20 is a literal integer But you can also declare a constant with the keyword const followed by its type, its name and a value
assignment, as follows: Example: int SomeFunction() { const float LENGTH = 10; const float WIDTH = 5.5; float Area; Area = LENGTH * WIDTH; ... }
Integer constantsAn integer constant can be a decimal, octal, or hexadecimal number. Examples: 15 // decimal signed integer 15u // decimal unsigned integer 0xFL // hexadecimal long integer (equals decimal 15) 0234 // octal 0x4b // hexadecimal Floating-point constantsA floating-point constant has an integer part, a decimal point, a fractional part, and can have an exponent part. The exponent is preceded by e or E. Examples: const float X = 3.14159; const double Y = 314159E-5; Boolean constantsA Boolean constant can be assigned one of two values: true or false. const bool SUNNY = true; const bool RAINING = false; Character constantsThe value of a character constant is enclosed in single quotes.
If certain characters are preceded by a backslash, they will have special meaning. Backslash is called the "escape" character. Examples of escape sequence codes: \\ \ character \' ' character \" " character \n Newline \r Carriage Return String constantsString constants are enclosed in double quotes. Examples: const String HELLO = "Hello, programmer"; const String LONGLINE = "This is a long line, a very long line, a really long line, a very very long line, a very very very long line"; |