what's an expression and expression statement in c++?
Asked Answered
D

8

34

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;
Drongo answered 20/9, 2011 at 3:55 Comment(3)
possible duplicate of Expression Versus StatementCondemn
I don't believe this is a duplicate. This question asks specifically about expression statements, while the other one asks about expressions vs. statements.Brynn
Also, that is tagged C# and this is tagged C++. When you're delving into syntax details like this, the difference is even bigger.Doll
B
32

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.

Brynn answered 20/9, 2011 at 4:28 Comment(0)
S
31

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.
Selfpossession answered 20/9, 2011 at 4:0 Comment(2)
not totally correct, assignment is a normal expression operator.Garofalo
@Garofalo x = 0 is an expression; x = 0; is a statement.Selfpossession
F
15

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.

Fritillary answered 3/6, 2016 at 13:33 Comment(0)
K
3

According to The C++ Programming Language by Bjarne Stroustrup Special(3rd) Edition, a statement is basically any declaration, function call, assignment, or conditional. Though, if you look at the grammar, it is much more complicated than that. An expression, in simple terms, is any math or logical operation(s).

The wikipedia links that ok posted in his answer can be of help too.

Kayo answered 20/9, 2011 at 4:6 Comment(0)
A
1

In my opinion,

a statement *states* the purpose of a code block. i.e. we say this block of code if(){} is an if-statement, or this x=42; is an expression statement. So code such as 42; serves no purporse, therefore, this is *not* a statement.

and,

an expression is any legal combination of symbols that represents a value (Credit to Webopedia); it combines variables and constants to produce new values(Quoted from Chapter 2 in The C Programming Language). Therefore, it also has a mathematical connotation. For instance, number 42 in x=42; is an expression (x=42; is not an expression but rather an expression statement), or func(x) is an expression because it will evaluate to something. On the contrary, int x; is not an expression because it is not representing any value.

Appose answered 10/1, 2018 at 10:13 Comment(0)
F
0

I think this excerpt from a technical book is most useful and clear.

Read the paragraphs till the start of 1.4.2 statements would be useful enough.

Fountain answered 23/3, 2018 at 3:22 Comment(0)
R
0

An expression is "a sequence of operators and operands that specifies a computation"

These are expressions:

1

2 + 2

"hi"

cout << "Hello, World!"

The last one is indeed an expression; << is the output operator, cout (of type ostream) and "Hello, World!" (string literals) are the operands. The operator returns the left-hand operand, so (cout << "Hello, ") << "World!" is also a valid expression but also not a statement.

An expression becomes an expression statement when it is followed by a semicolon:

1;

2 + 2;

"hi";

cout << "Hello, World!";
Rustcolored answered 28/4, 2022 at 1:34 Comment(0)
D
-3

An expression is part of a statement, OR a statement itself.

int x; is a statement and expression.

See this : http://en.wikipedia.org/wiki/Expression_%28programming%29

http://en.wikipedia.org/wiki/Statement_%28programming%29

Dorelle answered 20/9, 2011 at 3:57 Comment(5)
Wrong - it's a statement and a declaration. Since a declaration is never an expression statement and vice versa, it follows that this isn't an expression statement. Also, an expression (by itself) is never a statement and vice versa, so nothing is both.Doll
I agree with @MSalters. Expressions are not Statements: 42; might be the solution to everything but it still isn't a statement.Chagall
@itzJanuary: Bad example. It's in fact a statement, and not an expression. 42 is an expression and not a statement. The semicolon makes a large difference.Doll
@Doll 42; is not a valid statement in any language I know.Chagall
@itzJanuary: That might very well be - I don't know which languages you're familiar with. However, this is a C++ question, and in C++ it's a valid statement. See also Keith Thompson's answer, which uses the exact same example.Doll

© 2022 - 2024 — McMap. All rights reserved.