开发者

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

I've read that usually statements in c++ end with a semi-colon; so that might help explain what an expressi开发者_如何学运维on 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", 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.


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.


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.


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.


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!";


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜