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

前端 未结 7 1693
遇见更好的自我
遇见更好的自我 2020-12-04 12:42

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

相关标签:
7条回答
  • 2020-12-04 13:21

    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.

    0 讨论(0)
提交回复
热议问题