A literal is when you include a value in the source code (as opposed to referencing a variable or constant). For example:
int result = a + 5; // a is a variable with a value, 5 is a literal string name = "Jeff Atwood"; // name is a variable initialized // with the string literal, "Jeff Atwood" int[] array = new int[] {1, 2, 3}; // C
If a literal represents a certain quantity as a physical constant, it is better to give it a name instead of writing the same literal wherever you need it. That way, when you read the source code, you know what a number means, which is usually more important than its value (which can change anyway).
const int maxUsers = 100; const double gravitationalAcceleration = 9.8;
As a rule, the only numeric literals that I use (other than initializing constants as above) are 0 or 1, and sometimes 2, if I skip every other element in the loop. If the value of a number is more important than its actual value (it usually is), it is better to name it.
Matthew Crumley Jan 27 '09 at 20:58 2009-01-27 20:58
source share