Constants and Literals in C++


Constants and literals are values that remain fixed throughout a C++ program. They are used for storing unchanging data and can be of various data types. In this guide, we'll explore constants and literals in C++.


Constants

A constant is a named value that cannot be changed after its initial assignment. C++ provides two ways to declare constants: using the const keyword and using #define preprocessor directive.


Using const

With the const keyword, you can create constants like this:


const int maxScore = 100;
const double pi = 3.14159;

In this example, maxScore and pi are declared as constants with fixed values.


Using #define

You can also use the #define preprocessor directive to create constants:


#define MAX_SCORE 100
#define PI 3.14159

This approach creates symbolic constants that are replaced by their values during the preprocessing stage.


Literals

Literals are specific values used in expressions and assignments. There are different types of literals in C++:


  • Integer literals: Whole numbers, such as 42.
  • Floating-point literals: Numbers with decimal points, like 3.14.
  • Character literals: Single characters enclosed in single quotes, e.g., 'A'.
  • String literals: Text enclosed in double quotes, such as "Hello, World!".
  • Boolean literals: Represented by true or false.

Sample Code

Let's see an example of using constants and literals in C++:


#include <iostream>
using namespace std;
int main() {
const int maxScore = 100;
double circleArea = PI * 2 * 2; // Using a constant
char grade = 'A';
string greeting = "Hello, World!";
bool isTrue = true;
cout << "Max Score: " << maxScore << endl;
cout << "Circle Area: " << circleArea << endl;
cout << "Grade: " << grade << endl;
cout << "Greeting: " << greeting << endl;
cout << "Is True? " << isTrue << endl;
return 0;
}

In this code, we've used both constants (maxScore) and literals to perform calculations and assignments.


Conclusion

Constants and literals are essential for working with unchanging data in C++. They make your code more readable and maintainable. As you continue your C++ journey, you'll encounter various use cases for constants and different types of literals.