您可以在FOR LOOP语句中看到它的用法,但它在任何地方都是合法语法.你在其他地方发现它有什么用处,如果有的话?

推荐答案

C语言(以及C++)历史上是两种完全不同的编程风格的混合,可以称之为"语句编程"和"表达式编程".如您所知,每种过程性编程语言通常都支持sequencingbranching这样的基本 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.

C++相关问答推荐

如何从TPS特定的TGPT_PUBLIC数据 struct 中以OpenSSL的EVP_PKEY

gcc已编译的可执行文件TSB是否同时暗示最低有效字节和最低有效位?

为什么PLT表中没有push指令?

以c格式打印时间戳

来自stdarg.h的c中的va_args无法正常工作<>

我编译了一个新的c程序,并收到以下错误

自定义应用程序上的日志(log)轮换问题

在CLANG中调试预处理器宏

预先分配虚拟地址空间的区域

S在本文中的价值观到底出了什么问题?

仅从限制指针参数声明推断非混叠

如何在双向表中实现线程安全,每个条目仅使用4位,同时避免任何全局锁?

Zlib:解压缩大文件导致";无效代码长度设置";错误

使用正则表达式获取字符串中标记的开始和结束

将复合文字数组用作临时字符串缓冲区是否合理?

浮点正零何时不全为零?

通过GTK';传递回调参数;s g_signal_connect()导致C中出现意外值

为什么<到达*时不会转换为>?

在 C23 之前如何对空指针使用nullptr?

返回指向函数内声明的复合文字的指针是否安全,还是应该使用 malloc?