Note details

Types of Literal Constants in C++

BY u6dwl
August 24, 2025
Public
Private
8870 views

Nesso Academy Lecture: Types of Literal Constants in C++

Overview

In this lecture, we delve into the different types of literal constants available in C++. This extends from the foundational concepts of literal constants discussed in previous lectures.

Key Topics

1. Integer Literal

  • Definition: An integer literal is a number without a fractional part.
  • Notations:
    • Decimal Notation: Default method, digits from 0 to 9.
      int A = 10;
      
    • Hexadecimal Notation: Prefix 0x, digits from 0 to 9 and A-F.
      int B = 0x1A; // 26 in decimal
      
    • Octal Notation: Prefix 0, digits from 0 to 7.
      int C = 032; // 26 in decimal
      
    • Binary Notation: Prefix B, digits 0 and 1.
      int D = B1010; // 10 in decimal
      
  • Suffixes:
    • u or U: Unsigned integers.
    • l or L: Long integers.
    • ul, Lu: Unsigned long integers.
    • ll or LL: Long long integers.
    • ull, LLU: Unsigned long long integers.

2. Floating Point Literal

  • Definition: Represents a number with a fractional part or in exponential form.
  • Examples:
    • Double literals (default for floating-point literals): 4.5
    • Float literals (using f or F): 4.5f
      double X = 4.5;
      float Y = 4.5f;
      
  • Exponential Form: Uses e for scientific notation.
    double Z = 5.2e5; // 5.2 * 10^5
    

3. Character Literal

  • Definition: A single character enclosed in single quotes ('A').
  • Examples:
    • Character: 'A'
    • Escape characters (e.g., newline): '\n'
  • Internal Storage: Stored as integers based on ASCII values (e.g., 'A' is 65 in ASCII).
  • Arithmetic Operations: Can perform arithmetic operations due to integer storage.

4. String Literal

  • Definition: A sequence of characters enclosed in double quotes ("Hello").
  • Examples:
    • const char* name = "Alice";
    • std::string greet = "Hello World";
  • Characteristics:
    • Implicit null terminator (\0) at the end.
    • Concatenation of string literals when on separate lines.

5. Boolean Literal

  • Definition: Represents either true or false.
  • Examples:
    • bool isReady = true;
    • bool isEmpty = false;
  • Internal Representation:
    • true is equivalent to 1.
    • false is equivalent to 0.
  • Conversion: Nonzero values convert to true.

Conclusion

This lecture covers the types and representations of literal constants in C++. Understanding these types are crucial for effective programming in C++. Thank you for participating in this session. The next lecture will continue to expand on these concepts.