0

I understand that the concept literal is applied to whenever you represent a fixed value in source code, exactly as it is meant to be interpreted, vs. a variable or a constant, which are names for several of a class or one of them respectively.

But they are also opposed to expressions. I thought it was because they could incorporate variables. But even expressions like 1+2 are not (see first answer in What does the word "literal" mean?).

So, when I define a variable this way:

var=1+2 

1+2 is not a literal even though it is not a name and evaluates to a single value. I could then guess that it is because it doesn't represent the target value directly; in other words, a literal represents a value "exactly as it is".

But then how is it possible that a function like this one is a literal (as pointed it the same linked answer)?

(x) => x*x 
Community
  • 1
  • 1
Martin
  • 414
  • 7
  • 21

2 Answers2

1

Only anonymous functions can be literal because they are not bound to an identifier so (x)=>x*x is a literal because it is a anonymous function,or function literal but a

void my_func()
{#something}

is not a literal cause it is bound to an identifier; read these, https://en.wikipedia.org/wiki/Literal_(computer_programming) https://en.wikipedia.org/wiki/Anonymous_function

rdRahul
  • 543
  • 6
  • 13
1

Expressions can be divided into two general types: atomic expressions and composite expressions.

Composite expressions can be divided by operator, and so on; atomic expressions can be divided into variables, constants, and literals. I guess different authors might use other categories or boundaries here, so it might not be universal. But I will argue why this categorization might make sense.

It's fairly obvious why strings or numbers are literals, or why a sum isn't. A function call can be considered composite, as it operates on subexpressions - its parameters. A function definition does not operate on subexpressions. Only when the so defined function is called, that call passes parameters into the function. In a compiled language, the anonymous function will likely be replaced by a target address where the corresponding code is located - that memory location is obviously not dependent on any subexpression.

@rdRahul's answer references this Wikipedia article, which says that object literals, such as {"cat", "dog"} can be considered literals. This can be easily argued by pointing out that the object which is the value of the expression is just one opaque thing, such as a pointer to the memory location of the object.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Silly Freak
  • 4,061
  • 1
  • 36
  • 58