What does the word "literal" mean?

A literal is "any notation for representing a value within source code" (wikipedia)

(Contrast this with identifiers, which refer to a value in memory.)

Examples:

  • "hey" (a string)
  • false (a boolean)
  • 3.14 (a real number)
  • [1,2,3] (a list of numbers)
  • (x) => x*x (a function)
  • /^1?$|^(11+?)\1+$/ (a regexp)

Some things that are not literals:

  • std::cout (an identifier)
  • foo = 0; (a statement)
  • 1+2 (an expression)

A literal is a value that has been hard-coded directly into your source.

For example:

string x = "This is a literal";
int y = 2; // so is 2, but not y
int z = y + 4; // y and z are not literals, but 4 is
int a = 1 + 2; // 1 + 2 is not a literal (it is an expression), but 1 and 2 considered separately are literals

Some literals can have a special syntax, so you know what type the literal is:

//The 'M' in 10000000M means this is a decimal value, rather than int or double.
var accountBalance = 10000000M; 

What sets them apart from variables or resources is the compiler can treat them as constants or perform certain optimizations with code where they are used, because it's certain they won't change.


A literal is an assignment to an explicit value, such as

int i = 4;  // i is assigned the literal value of '4'
int j = i   // j is assigned the value of i.  Since i is a variable,  
            //it can change and is not a 'literal'

EDIT: As pointed out, assignment itself has nothing to do with the definition of a literal, I was using assignment in my example, but a literal can also be passed into a method, etc.