Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🟢 Foundation  ·  Lesson 11

Constants and Literals in C++

In this lesson: Make constants in C++ with const, constexpr and #define, and learn literal types — with examples. In Hindi & English.

Constants vs literals

A literal is a value written directly in the source code: 100, 3.14, 'A', "Priya", true. A constant is a *named* value that cannot be changed once it is set, for example const int MAX_MARKS = 100;. Constants give meaning to literals and protect them from accidental changes.

Write the number once, give it a name, and use the name everywhere. If the rule changes, you edit one line.

Types of literals

KindExamplesType
Integer42, -7, 1000000int (or larger if needed)
Integer, other bases0x2A (hex), 052 (octal), 0b101010 (binary, C++14)int
Integer suffixes42u, 42L, 42LL, 42ULLunsigned / long / long long
Floating point3.14, 2.5e3, 1.0fdouble (float with f)
Character'A', '7', '\n', '\t'char
String"Hello", "C:\\temp"array of const char
Booleantrue, falsebool
Pointernullptrstd::nullptr_t

C++14 also allows digit separators for readability: 1'000'000 is the same as 1000000.

C++
#include <iostream>
int main() {
    std::cout << 0x2A << " " << 052 << " " << 0b101010 << "\n";
    std::cout << 2.5e3 << " " << 'A' << " " << true << "\n";
    std::cout << 1'000'000 << "\n";
    return 0;
}
42 42 42 2500 A 1 1000000

Notice that true prints as 1; use std::boolalpha to print the word true.

Escape sequences in character and string literals

SequenceMeaning
\nNew line
\tTab
\\Backslash
\' and \"Single / double quote
\0Null character (end of a C string)

The const keyword

const makes a variable read-only after it is initialised. It must be given a value when declared.

C++
#include <iostream>
int main() {
    const int MAX_MARKS = 100;
    const double PASS_PERCENT = 33.0;

    int obtained = 72;
    double percent = obtained * 100.0 / MAX_MARKS;
    std::cout << "Percent: " << percent << "\n";
    std::cout << (percent >= PASS_PERCENT ? "Pass" : "Fail") << "\n";

    // MAX_MARKS = 90;   // error: assignment of read-only variable
    return 0;
}
Percent: 72 Pass

const is also used with references and pointers (const std::string& name) and on member functions (void show() const;), which you will meet in later lessons.

constexpr: constants known at compile time

constexpr (C++11) promises that a value can be computed by the compiler. Use it for values that must be fixed before the program runs, such as array sizes.

C++
constexpr int SUBJECTS = 5;
int marks[SUBJECTS];            // OK: size known at compile time

constexpr int square(int x) { return x * x; }
constexpr int AREA = square(4); // computed by the compiler: 16

A const initialised from user input is still const, but it is not constexpr:

C++
int n;
std::cin >> n;
const int size = n;        // fine: cannot change later
// constexpr int s2 = n;   // error: n is not known at compile time

#define macros

The old C way is a preprocessor macro:

C++
#define PI 3.14159

The preprocessor replaces every PI with 3.14159 before compilation. It has no type and no scope, and mistakes are hard to trace. In C++ prefer constexpr double PI = 3.14159;. See preprocessor directives for when macros are still useful.

enum constants

When a variable can take one of a few named values, use an enumeration:

C++
enum class Grade { A, B, C, D, F };
Grade g = Grade::B;

See enums in C++.

const vs constexpr vs #define

Feature#defineconstconstexpr
Has a typeNoYesYes
Obeys scopeNoYesYes
Value fixed at compile timeText replacedNot necessarilyYes, always
Can be array sizeYesOnly if initialised with a constant expressionYes
Visible in debuggerNoYesYes

Common mistakes

  • Declaring const int x; without a value — a const must be initialised.
  • Writing 'Hello' (single quotes) for a string; single quotes are for one character.
  • Forgetting that 07 and 010 are octal: 010 is 8, not 10.
  • Integer division surprise: 72 / 100 * 100 is 0; write 72 * 100.0 / 100.
  • Using #define for typed constants and getting unexpected results in expressions, e.g. #define TWICE 1+1 makes TWICE*3 equal 4.
🏋️ Practice

Write a program with constexpr int DAYS_IN_WEEK = 7, const double GST = 0.18 and an enum class Day. Read the price of an item, print it with GST, and print how many hours are in a week using the constant.

Summary

  • Literals are fixed values in code; constants are named, read-only values.
  • Literal kinds: integer, floating, character, string, boolean and nullptr.
  • const = read-only after initialisation; constexpr = known at compile time.
  • Prefer const/constexpr over #define.
  • Use enum class for a fixed set of named values.

Related: variables and data types, type casting, enums.

Frequently Asked Questions

What is the difference between a constant and a literal in C++?
A literal is a fixed value written directly in the code, such as 100, 3.14, 'A' or "Aman". A constant is a named value that cannot change after it is set, such as const int MAX = 100;. Constants usually get their value from a literal.
What is the difference between const and constexpr in C++?
const means the value cannot be changed after initialisation, but it may be known only at run time. constexpr means the value must be computable at compile time, so it can be used where the compiler needs a fixed number, such as an array size or a template argument.
Should I use #define or const in C++?
Prefer const or constexpr. They have a type, obey scope rules and show up in the debugger. #define is plain text substitution done by the preprocessor, so it has no type checking and can cause surprising errors.
What are the types of literals in C++?
C++ has integer literals (42, 0x2A, 052, 0b101010), floating-point literals (3.14, 2.5e3), character literals ('A', '\n'), string literals ("Hello"), boolean literals (true, false) and the pointer literal nullptr.
← Back to C++ Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicNamespaces in C++ Your progress: 11 / 81 (14%) · Lesson 12 / 81 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free