Expression statements
Expression statements
Certain expressions (like x = 5
) are useful by themselves (in this case, to assign the value 5
to the variable x
). However, we mentioned above that expressions cannot be executed by themselves -- they must exist as part of a statement. So how can we use such expressions?
Fortunately, it’s easy to convert any expression into an equivalent statement (called an expression statement). An expression statement is a statement that consists of an expression followed by a semicolon. When the statement is executed, the expression will be evaluated.
Thus, we can take any expression (such as x = 5
), and turn it into an expression statement (x = 5;
) that will compile.
The result of an expression statement is discarded before the next statement is executed.
We can also make expression statements that compile but have no effect. For example, the expression statement (2 * 3;
) is a expression statement whose expression evaluates to the result value of 6, which is then discarded. While syntactically valid, such expression statements are useless. Some compilers (such as gcc and Clang) will produce warnings if they can detect that an expression statement is useless.
Comments
Post a Comment