c - `printf("…") || printf("…") || printf("…")` 的语义

标签 c

我想知道以下语句在 C 中会打印什么?

printf("hello\n") || (printf("goodbye\n") || printf("world\n"));

我通常习惯于使用“cout”在 C 中打印一些内容。此外,我对这种方式使用的管道和双管道运算符感到困惑。谢谢!

最佳答案

首先,cout 是 C++ 的发明,从未回到 C,也永远不会。

接下来,printf 返回打印的字符数,因此第一次调用返回非零。

由于 || 是短路 bool 或,因此不会执行以下 printf 调用。

(| 是按位或,因此不是短路。添加是因为您正在谈论单管道并且 @Leeor 链接了这样的问题。)

最终结果:打印 hello\n:5 个字符+换行符(将被翻译,因为 stdin 是文本模式(Unixoid 上的身份转换))。

7.21.6.3 The printf function

Synopsis

#include <stdio.h>
int printf(const char * restrict format, ...);

Description
2 The printf function is equivalent to fprintf with the argument stdout interposed before the arguments to printf.
Returns
3 The printf function returns the number of characters transmitted, or a negative value if an output or encoding error occurred.

6.5.12 Bitwise inclusive OR operator

Synopsis
[...]
Constraints
2 Each of the operands shall have integer type.
Semantics
3 The usual arithmetic conversions are performed on the operands.
4 The result of the | operator is the bitwise inclusive OR of the operands (that is, each bit in the result is set if and only if at least one of the corresponding bits in the converted operands is set).

6.5.14 Logical OR operator

Synopsis
[...]
Constraints
2 Each of the operands shall have scalar type.
Semantics
3 The || operator shall yield 1 if either of its operands compare unequal to 0; otherwise, it yields 0. The result has type int.
4 Unlike the bitwise | operator, the || operator guarantees left-to-right evaluation; if the second operand is evaluated, there is a sequence point between the evaluations of the first and second operands. If the first operand compares unequal to 0, the second operand is not evaluated.

关于c - `printf("…") || printf("…") || printf("…")` 的语义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26475907/

相关文章:

c - 如何在 C 程序中的 char 数组中分配输入(来自 echo 命令)

c - C 中的变量替换(在变量名本身中)

c - 基本 C Multi 中的高斯乔丹方法

c - 如何设置列表框背景颜色

c - C 中运算符 == 的返回类型

c - 使用c从/proc/net/dev解析txBytes,rxBytes,rxPackets,txPackets

c - 声明和定义相互引用的初始化常量结构的最佳方法

c - 将一维固定数组传递给二维指针函数

c++ - 为什么编译器只向后查找类型和函数声明?

c - printf 在类型与类型说明符不匹配的情况下如何工作?