Lesson 14 +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

printf("%d\n", 42);        // integer literal
printf("%f\n", 3.14);      // floating-point literal
printf("%c\n", 'A');       // char literal (single quotes)
printf("%s\n", "hello");   // string literal (double quotes)
  • 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.

Writing the bases

Numbers can be written in other bases:

  • Decimal: 42
  • Octal, start with a 0: 052 (that's decimal 42).
  • Hexadecimal, start with 0x: 0x2A (decimal 42).

Suffixes to fix type

A small letter after the number picks an exact type:

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

TL;DR

  • A literal is a fixed value typed directly in the code.
  • Kinds: integers 42, floats 3.14, chars 'A', strings "hello".
  • Number bases: 0 = octal, 0x = hex.
  • Suffixes like f, L, U, LL set the exact type.