0
0
C++programming~5 mins

Constants and literals in C++

Choose your learning style9 modes available
Introduction

Constants and literals let you use fixed values in your program that do not change. This helps keep your code clear and safe.

When you want to use a value that should never change, like the number of days in a week.
When you want to make your code easier to read by giving a name to a fixed value.
When you want to avoid mistakes by preventing accidental changes to important values.
When you want to use fixed text or numbers directly in your program.
When you want to improve performance by using fixed values known at compile time.
Syntax
C++
const type name = value;

// Examples:
const int DAYS_IN_WEEK = 7;
const double PI = 3.14159;

const keyword makes a variable constant, so its value cannot change after initialization.

Literals are fixed values like numbers (42), characters ('a'), or strings ("hello") used directly in code.

Examples
This creates a constant integer named MAX_SCORE with value 100.
C++
const int MAX_SCORE = 100;
This creates a constant character for the newline symbol.
C++
const char NEWLINE = '\n';
This creates a constant double for a tax rate of 7%.
C++
const double TAX_RATE = 0.07;
This creates a constant pointer to a string literal "Hello!".
C++
const char* const GREETING = "Hello!";
Sample Program

This program shows how to declare constants and use them in output. It also shows that trying to change a constant causes an error.

C++
#include <iostream>

int main() {
    const int DAYS_IN_WEEK = 7;
    const double PI = 3.14159;
    const char NEWLINE = '\n';

    std::cout << "Days in a week: " << DAYS_IN_WEEK << NEWLINE;
    std::cout << "Value of PI: " << PI << NEWLINE;
    std::cout << "This is a newline character: " << NEWLINE;

    // Uncommenting the next line will cause a compile error because DAYS_IN_WEEK is constant
    // DAYS_IN_WEEK = 8;

    return 0;
}
OutputSuccess
Important Notes

Constants must be initialized when declared.

Trying to change a constant value after initialization will cause a compile-time error.

Literals are the actual fixed values you write in your code, like numbers or text.

Summary

Constants hold fixed values that cannot change during program execution.

Literals are the actual fixed values written directly in code.

Using constants makes your code safer and easier to understand.