我试图彻底理解一个陈述和一个表达之间的区别
但是我发现它甚至在阅读了这个答案之后就会感到困惑.
表达式和声明
请看下面的内容:
std::cout << "Hello there? " ;
Run Code Online (Sandbox Code Playgroud)
我可以说它是一个声明,因为它以分号结尾但我也可以说它
是一个表达式,因为我有一个ostream,一个输出运算符和一个字符串文字
,这个表达式产生的值是左手操作数.
哪一个是正确的?
Rei*_*ica 10
让我们看看C++语法可以告诉我们的内容:
statement:
labeled-statement
attribute-specifier-seq_opt expression-statement
attribute-specifier-seq_opt compount-statement
attribute-specifier-seq_opt selection-statement
attribute-specifier-seq_opt iteration-statement
attribute-specifier-seq_opt jump-statement
declaration-statement
attribute-specifier-seq_opt try-block
expression-statement:
expression_opt ';'
Run Code Online (Sandbox Code Playgroud)
所以这是一个声明; 特别是,一个"表达式语句",它由一个(可能是空的)表达式后跟一个分号组成.换一种说法,
std::cout << "Hello there? "
Run Code Online (Sandbox Code Playgroud)
是一种表达,而
std::cout << "Hello there? " ;
Run Code Online (Sandbox Code Playgroud)
是一份声明.
哪一个是正确的?
两者:它是一个表达式声明.C和C++允许您将表达式放入代码体中,添加分号并使其成为语句.
以下是一些例子:
x++; // post-increment produces a value which you could use
a = 5; // Assignment produces a value
max(a, b); // Call of a non-void function is an expression
2 + x; // This calculation has no side effects, but it is allowed
Run Code Online (Sandbox Code Playgroud)
请注意,在C和C++的特定情况下也是如此,但在其他语言的情况下可能不适用.例如,上面列表中的最后一个表达式语句在Java或C#中将被视为无效.