Expression Versus Statement

前端 未结 21 1753
别那么骄傲
别那么骄傲 2020-11-22 11:54

I\'m asking with regards to c#, but I assume its the same in most other languages.

Does anyone have a good definition of expressions and statements

21条回答
  •  不思量自难忘°
    2020-11-22 12:05

    I am not really satisfied with any of the answers here. I looked at the grammar for C++ (ISO 2008). However maybe for the sake of didactics and programming the answers might suffice to distinguish the two elements (reality looks more complicated though).

    A statement consists of zero or more expressions, but can also be other language concepts. This is the Extended Backus Naur form for the grammar (excerpt for statement):

    statement:
            labeled-statement
            expression-statement <-- can be zero or more expressions
            compound-statement
            selection-statement
            iteration-statement
            jump-statement
            declaration-statement
            try-block
    

    We can see the other concepts that are considered statements in C++.

    • expression-statements is self-explaining (a statement can consist of zero or more expressions, read the grammar carefully, it's tricky)
    • case for example is a labeled-statement
    • selection-statements are if if/else, case
    • iteration-statements are while, do...while, for (...)
    • jump-statements are break, continue, return (can return expression), goto
    • declaration-statement is the set of declarations
    • try-block is statement representing try/catch blocks
    • and there might be some more down the grammar

    This is an excerpt showing the expressions part:

    expression:
            assignment-expression
            expression "," assignment-expression
    assignment-expression:
            conditional-expression
            logical-or-expression assignment-operator initializer-clause
            throw-expression
    
    • expressions are or contain often assignments
    • conditional-expression (sounds misleading) refers to usage of the operators (+, -, *, /, &, |, &&, ||, ...)
    • throw-expression - uh? the throw clause is an expression too

提交回复
热议问题