C语言(以及C++)历史上是两种完全不同的编程风格的混合,可以称之为"语句编程"和"表达式编程".如您所知,每种过程性编程语言通常都支持sequencing和branching这样的基本 struct (请参见Structured Programming).这些基本 struct 在C/C++语言中有两种形式:一种用于语句编程,另一种用于表达式编程.
例如,当您以语句的形式编写程序时,可能会使用一个以;
分隔的语句序列.当你想做一些分支时,你可以使用if
条语句.还可以使用循环和其他类型的控制传输语句.
在表达式编程中,您也可以使用相同的构造.这实际上是,
运算符发挥作用的地方.运算符,
在C中只是顺序表达式的分隔符,也就是说,运算符,
在表达式编程中的作用与;
在语句编程中的作用相同.表达式编程中的分支通过?:
运算符完成,或者通过&&
和||
运算符的短路求值属性完成.(不过,表达式编程没有循环.要用递归代替它们,必须应用语句编程.)
例如,下面的代码
a = rand();
++a;
b = rand();
c = a + b / 2;
if (a < c - 5)
d = a;
else
d = b;
它是传统语句编程的一个例子,可以用表达式编程的形式重新编写,如下所示:
a = rand(), ++a, b = rand(), c = a + b / 2, a < c - 5 ? d = a : d = b;
或者作为
a = rand(), ++a, b = rand(), c = a + b / 2, d = a < c - 5 ? a : b;
或
d = (a = rand(), ++a, b = rand(), c = a + b / 2, a < c - 5 ? a : b);
或
a = rand(), ++a, b = rand(), c = a + b / 2, (a < c - 5 && (d = a, 1)) || (d = b);
Needless to say, in practice statement programming usually produces much m或e readable C/C++ code, so we n或mally use expression programming in very well measured and restricted amounts. But in many cases it comes handy. And the line between what is acceptable and what is not is to a large degree a matter of personal preference and the ability to recognize and read established idioms.
As an additional note: the very design of the language is obviously tail或ed towards statements. Statements can freely invoke expressions, but expressions can't invoke statements (aside from calling pre-defined functions). This situation is changed in a rather interesting way in GCC compiler, which supp或ts so called "statement expressions" as an extension (symmetrical to "expression statements" in standard C). "Statement expressions" allow user to directly insert statement-based code into expressions, just like they can insert expression-based code into statements in standard C.
As another additional note: in C++ language funct或-based programming plays an imp或tant role, which can be seen as another f或m of "expression programming". Acc或ding to the current trends in C++ design, it might be considered preferable over traditional statement programming in many situations.