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.

For advanced readers

An expression whose result is discarded is called a discarded-value expression). Expression statements are by far the most common type of discarded-value expressions.

Other discarded-value expressions include the left operand of the comma operator, and any expression that is cast to type void.

Useless expression statements

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

Popular posts from this blog

Whiteboarding Interviews

Version Control with Git: A Beginner’s Guide

Callback function in JavaScript