I’ve read that usually statements in c++ end with a semi-colon; so that might help explain what an expression statement would be. But then what would you call an expression by giving an example?
In this case, are both just statements or expression statements or expressions?
int x;
x = 0;
An expression is “a sequence of operators and operands that specifies a computation” (that’s the definition given in the C++ standard). Examples are
42,2 + 2,"hello, world", andfunc("argument"). Assignments are expressions in C++; so are function calls.I don’t see a definition for the term “statement”, but basically it’s a chunk of code that performs some action. Examples are compound statements (consisting of zero or more other statements included in
{…}), if statements, goto statements, return statements, and expression statements. (In C++, but not in C, declarations are classified as statements.)The terms statement and expression are defined very precisely by the language grammar.
An expression statement is a particular kind of statement. It consists of an optional expression followed by a semicolon. The expression is evaluated and any result is discarded. Usually this is used when the statement has side effects (otherwise there’s not much point), but you can have a expression statement where the expression has no side effects. Examples are:
The null statement is a special case. (I’m not sure why it’s treated that way; in my opinion it would make more sense for it to be a disinct kind of statement. But that’s the way the standard defines it.)
Note that
is a statement, but it’s not an expression statement. It contains an expression, but the expression (plus the
;) doesn’t make up the entire statement.