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
To add to the excellent explanation by FractionalRadix, it's worth mentioning that sometimes the line between expressions and statements can seem a little blurry (at least to the observer — the language specification will almost certainly define the boundaries clearly and precisely).
For example, in C we have the expression ++i
, which means "add one to the value of i
and return the new value". This is an expression because it yields a value, but it also makes a change to the program state. Therefore you can use it as a "pure" expression and assign it to something else:
int iNew = ++i; // increment i, put incremented value into iNew
or you can use it as a statement in its own right:
++i; // increment i and do nothing else
Also in C, a simple assignment can be an expression as well as a statement, e.g.
int x = 2; // statement
int y = (x = 3); // y and x are now both equal to 3
Informally, you can think of an expression as something you can (but don't necessarily have to) put on the right-hand side of an assignment operation.
Languages may also differ in which constructs they treat as statements or expressions. In Rust, an if
construct is actually an expression, not a statement, and can be assigned as a value:
let x = if (y == 2) { 5 } else { 10 };
If you try this in C you'll get a compilation error because if
is a statement and does not evaluate to a value:
int x = if (y == 2) { 5; } else { 10; } // INVALID; won't compile
But in Python, you can't treat an assignment as an expression like you can in C, unless you use a special recently-introduced syntax:
x = 2
y = (x = 3)
^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
y = (x := 3) # x and y are now both 3
1 comment thread