Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Comments on What are statements and expressions?
Parent
What are statements and expressions?
When I have tried to read technical explanations of the syntax rules for programming languages, and when I am trying to decipher error messages, I often encounter the terms expression and statement. It comes across that these two are related to each other somehow.
I understand that these terms have something to do with the actual code written in a programming language - not, for example, special sorts of values calculated by the program when it runs - right? But what do they mean exactly? How can I use these concepts to improve my understanding of a programming language?
Post
In computer programming, an expression is something that yields a value.
A statement performs an action.
For example, let us look at some pseudocode. Let's assume that we want to calculate the sum of 3 variables:
sum = a + b + c;
print(sum);
print(sum);
is a statement: it performs an action.
a + b + c
is an expression: it yields a value.
Now you may be wondering: is sum = a + b + c
a statement, or an expression?
The answer is that it's a statement, but it contains an expression. a + b + c
yields a value, and then an action is taken: the value is assigned to a variable.
In this example, we have an arithmetic expression. But most operations on strings and booleans are also expressions!
For example, we could have a conditional:
if (a > 3 && p == 5) { ... }
In this condition statement, the part a > 3 && p == 5
is an expression. A boolean expression.
Or, we might be concatenating strings:
fullName = firstName + " " + lastName;
In this line of code, firstName + " " + lastName
is a string expression. It yields a value. The line as a whole is a statement: it evaluates an expression and stores the result in a new variable.
In general, expressions occur inside statements. An expression yields a value, but after you have your value, you'll want to do something with it - store it somewhere, or output it, or send it as an argument to another function.
1 comment thread