what's an expression and expression statement in c++?

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", and func("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:

x = 42; // the expression happens to be an assignment

func("argument");

42; // no side effects, allowed but not useful

; // a null statement

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

return 42;

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.


These are expressions (remember math?):

1
6 * 7
a + b * 3
sin(3) + 7
a > b
a ? 1 : 0
func()
mystring + gimmeAString() + std::string("\n")

The following are all statements:

int x;                            // Also a declaration.
x = 0;                            // Also an assignment.
if(expr) { /*...*/ }              // This is why it's called an "if-statement".
for(expr; expr; expr) { /*...*/ } // For-loop.

A statement is usually made up of an expression:

if(a > b)           // a > b is an expr.
    while(true)     // true is an expr.
        func();     // func() is an expr.

To understand what is an expression statement, you should first know what is an expression and what is an statement.

An expression in a programming language is a combination of one or more explicit values, constants, variables, operators, and functions that the programming language interprets (according to its particular rules of precedence and of association) and computes to produce ("to return", in a stateful environment) another value. This process, as for mathematical expressions, is called evaluation.

Source: https://en.wikipedia.org/wiki/Expression_(computer_science)

In other words expressions are a sort of data items. They can have single or multiple entities like constants and variables. These entities may be related or connected to each other by operators. Expressions may or may not have side effects, in that they evaluate to something by means of computation which changes a state. For instance numbers, things that look like mathematical formulas and calculations, assignments, function calls, logical evaluations, strings and string operations are all considered expressions.

function calls: According to MSDN, function calls are considered expressions. A function call is an expression that passes control and arguments (if any) to a function and has the form: expression (expression-list opt) which is invoked by the ( ) function operator.

source: https://msdn.microsoft.com/en-us/library/be6ftfba.aspx

Some examples of expressions are:

46
18 * 3 + 22 / 2
a = 4
b = a + 3
c = b * -2
abs(c)
b >= c
c
"a string"
str = "some string"
strcat(str, " some thing else")
str2 = "some string" + " some other string" // in C++11 using string library

Statements are fragments of a program that execute in sequence and cause the computer to carry out some definite action. Some C++ statement types are:

  • expression statements;
  • compound statements;
  • selection statements;
  • iteration statements;
  • jump statements;
  • declaration statements;
  • try blocks;
  • atomic and synchronized blocks (TM TS).

Source: http://en.cppreference.com/w/cpp/language/statements

I've read usually statements in c++ ends with a semicon;

Yes usually! But not always. Consider the following piece of code which is a compound statement but does not end with a semicolon, rather it is enclosed between two curly braces:

{   // begining of a compound statement
    int x;    // A declaration statement
    int y;
    int z;
    x = 2;    // x = 2 is an expression, thus x = 2; with the trailing semicolon is an expression statement
    y = 2 * x + 5;
    if(y == 9) {    // A control statement
        z = 52;
    } else {        // A branching statement of a control statement
        z = 0;
    }
 }    // end of a compound statement

By now, as you might be guessing, an expression statement is any statement that has an expression followed by a semicolon. According to MSDN an expression statement is a statement that causes the expressions to be evaluated. No transfer of control or iteration takes place as a result of an expression statement.

Source: https://msdn.microsoft.com/en-us/library/s7ytfs2k.aspx

Some Examples of expression statements:

x = 4;
y = x * x + 10;
radius = 5;
pi = 3.141593;
circumference = 2. * pi * radius;
area = pi * radius * radius;

Therefore the following can not be considered expression statements since they transfer the control flow to another part of a program by calling a function:

printf("The control is passed to the printf function");
y = pow(x, 2);

side effects: A side effect refers to the modification of a state. Such as changing the value of a variable, writing some data on a disk showing a menu in the User Interface, etc.

Source: https://en.wikipedia.org/wiki/Side_effect_(computer_science)

Note that expression statements don't need to have side effects. That is they don't have to change or modify any state. For example if we consider a program's control flow as a state which could be modified, then the following expression statements won't have any side effects over the program's control flow:

a = 8;
b = 10 + a;
k++;

Wheres the following expression statement would have a side effect, since it would pass the control flow to sqrt() function, thus changing a state:

d = sqrt(a);    // The control flow is passed to sqrt() function

If we consider the value of a variable as a state as well, modifying it would be a side effect thus all of expression statements above have side effects, because they all modify a state. An expression statement that does not have any side effect is not very useful. Consider the following expression statements:

x = 7;  // This expression statement sets the value of x to 7
x;      // This expression statement is evaluated to 7 and does nothing useful 

In the above example x = 7; is a useful expression statement for us. It sets the value of x to 7 by = the assignment operator. But x; evaluates to 7 and it doesn't do anything useful.

Tags:

C++