Expression Versus Statement

前端 未结 21 1751
别那么骄傲
别那么骄傲 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

    Expressions can be evaluated to get a value, whereas statements don't return a value (they're of type void).

    Function call expressions can also be considered statements of course, but unless the execution environment has a special built-in variable to hold the returned value, there is no way to retrieve it.

    Statement-oriented languages require all procedures to be a list of statements. Expression-oriented languages, which is probably all functional languages, are lists of expressions, or in tha case of LISP, one long S-expression that represents a list of expressions.

    Although both types can be composed, most expressions can be composed arbitrarily as long as the types match up. Each type of statement has its own way of composing other statements, if they can do that all. Foreach and if statements require either a single statment or that all subordinate statements go in a statement block, one after another, unless the substatements allow for thier own substatements.

    Statements can also include expressions, where an expression doesn't really include any statements. One exception, though, would be a lambda expression, which represents a function, and so can include anything a function can iclude unless the language only allows for limited lambdas, like Python's single-expression lambdas.

    In an expression-based language, all you need is a single expression for a function since all control structures return a value (a lot of them return NIL). There's no need for a return statement since the last-evaluated expression in the function is the return value.

提交回复
热议问题