Beginner Topic 4 of 54 Programming Fundamentals
Expressions
Combinations of values and operators that evaluate to a single result.
How it works
An expression is any piece of code that produces a value, built recursively from literals, variables, operators and function calls. The interpreter evaluates sub-expressions first and then combines their results, following precedence and associativity rules. A statement, by contrast, performs an action and may not yield a value, although many languages treat assignments and conditionals as expressions too.
Step-by-step walkthrough
- The expression 2 + 3 * 4 is parsed into a tree.
- The innermost operation 3 * 4 is evaluated first giving 12.
- Then 2 + 12 is evaluated giving 14.
- An expression always reduces to a single value.
Where it is used
Conditions in if statements, arguments to functions, the right-hand side of assignments and return values all take expressions, for example (a + b) * c > limit. Spreadsheet formulas and query filters are expression languages in their own right.
Common pitfall
Side effects inside expressions, such as i++ in the middle of a larger expression, make code hard to read and can be order-dependent or even undefined in some languages. Overly long expressions are hard to debug; break them into named intermediate variables.
Where it fits in the course
Expressions is topic 4 of 54 in Programming Fundamentals, rated Beginner. It follows Operators. The next topic is Type Casting.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Programming Fundamentals quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Programming Fundamentals quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Expressions?
Where do people use Expressions?
What is the most common mistake with Expressions?
What should I learn before this topic?
How can I practice it?
Is Expressions hard to learn?
How long does it take to learn Expressions?
Which topics are related to Expressions?
What should I study after Expressions?
Related topics
- Operators (Programming Fundamentals)
- Type Casting (Programming Fundamentals)
- Data Types (Programming Fundamentals)
- Input and Output (Programming Fundamentals)
- Regular Expressions in Theory (Theory & Discrete Math)
- Common Table Expressions (Databases)