Search code examples
expressioncomputer-science

Is a single constant value considered an expression?


After reading this answer on a CSS question, I wonder:

In Computer Science, is a single, constant value considered an expression?

In other words, is 7px an expression? What about just 7?

Quoting Wikipedia, emphasis mine:

An expression in a programming language is a combination of one or more explicit values, constants, variables, operators, and functions that the programming language interprets [...] and computes to produce [...] another value. This process, as for mathematical expressions, is called evaluation.

Quoting MS Docs, emphasis mine:

An expression is a sequence of one or more operands and zero or more operators that can be evaluated to a single value, object, method, or namespace. Expressions can consist of a literal value [...].

These both seems to indicate that values are expressions. However, one could argue that a value will not be evaluated, as it is already only a value, and therefore doesn't qualify.

Quoting Techopedia, emphasis mine:

[...] In terms of structure, experts point out that an expression inherently needs at least one 'operand’ or value that is acted on, and must have one or more operators. [...]

This suggests that even x does not qualify as expression as it is lacking one or more operators.


Solution

  • It depends on the exact definition of course, but under most definitions expressions are defined recursively with constants being one of the basis cases. So, yes, literal values are special cases of expressions.

    You can look at grammars for various languages such as the one for Python

    If you trace through the grammar you see that an expr can be an atom which includes number literals. The fact that number literals are Python expressions is also obvious when you consider productions like:

    comparison: expr (comp_op expr)*
    

    This is the production which captures expressions like x < 7, which wouldn't be captured if 7 isn't a valid expression.