Lesson 12 +10 XP

Literals

Literals

A literal is a fixed value written directly in the source code. Its value is literally whatever you typed.

The common kinds

cout << 42 << '\n';        // integer literal
cout << 3.14 << '\n';      // floating-point literal
cout << 'A' << '\n';       // char literal (single quotes)
cout << "hello" << '\n';   // string literal (double quotes)
cout << true << '\n';      // boolean literal
  • 42 - an integer (whole number).
  • 3.14 - a floating-point (number with a fraction).
  • 'A' a char literal - one single character, single quotes.
  • "hello" a string literal - text, double quotes.
  • true - a boolean (true or false).

Why they matter

Literals are our "fixed data": unlike variables, they never change. Every price, name, or message that's always the same starts life as a literal.

Writing the bases (C++14)

Numbers can be written in other bases to make reading easier:

  • Decimal: 42
  • Octal, start with a 0: 052 (that's decimal 42).
  • Hexadecimal, start with 0x: 0x2A (decimal 42).
  • Binary, start with 0b (C++14+): 0b101010 (decimal 42).

Suffixes to fix type

A small letter after the number picks an exact type:

3.14f;    // float
42L;      // long
42U;      // unsigned
42ULL;    // unsigned long long

Use suffixes when you need a very specific type; otherwise the default is fine.

TL;DR

  • A literal is a fixed value typed directly in the code.
  • Kinds: integers 42, floats 3.14, chars 'A', strings "hello", booleans true.
  • Number bases: 0 = octal, 0x = hex, 0b = binary (C++14+).
  • Suffixes like f, L, U, ULL set the exact type.