gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:06:13 27 4
gpt4 key购买 nike

我想知道以下语句在 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com