c++ - cout << "\n"[a==N] 是什么意思?做?

标签 c++ cout string-literals

在以下示例中:

cout<<"\n"[a==N];

我不知道 [] 选项在 cout 中的作用,但是当 a 的值时它不会打印换行符等于 N

最佳答案

I have no clue about what the [] option does in cout

这实际上不是 cout 选项,发生的是 "\n"string literal .字符串文字的类型为 array of n const char[] 只是一个字符数组的索引,在这种情况下包含:

\n\0

注意 \0 被附加到所有字符串字面量。

== 运算符导致 truefalse,因此索引将为:

  • 0 如果为 false,如果 a 不等于 N 导致 \n
  • 1 如果为真,如果 a 等于 N 导致 \0

这是相当神秘的,可以用一个简单的 if 代替。

引用 C++14 标准(Lightness 确认草案与实际标准匹配),最接近的草案是 N39362.14.5 部分字符串文字 [lex.string] 说(强调我的):

string literal has type “array of n const char”, where n is the size of the string as defined below, and has static storage duration (3.7).

和:

After any necessary concatenation, in translation phase 7 (2.2), ’\0’ is appended to every string literal so that programs that scan a string can find its end.

4.5[conv.prom] 说:

A prvalue of type bool can be converted to a prvalue of type int, with false becoming zero and true becoming one.

将空字符写入文本流

声称将空字符 (\0) 写入文本流是未定义的行为。

据我所知,这是一个合理的结论,cout 是根据 C 流定义的,从 27.4.2 [ narrow.stream.objects] 说:

The object cout controls output to a stream buffer associated with the object stdout, declared in <cstdio> (27.9.2).

7.21.2 Streams 节中的 C11 草案标准说:

[...]Data read in from a text stream will necessarily compare equal to the data that were earlier written out to that stream only if: the data consist only of printing characters and the control characters horizontal tab and new-line;

打印字符7.4中有介绍 字符处理:

[...]the term control character refers to a member of a locale-specific set of characters that are not printing characters.199) All letters and digits are printing characters.

脚注 199 说:

In an implementation that uses the seven-bit US ASCII character set, the printing characters are those whose values lie from 0x20 (space) through 0x7E (tilde); the control characters are those whose values lie from 0 (NUL) through 0x1F (US), and the character 0x7F (DEL).

最后我们可以看到发送空字符的结果没有被指定,我们可以看到这是未定义的行为,来自 4 部分的一致性,它说:

[...]Undefined behavior is otherwise indicated in this International Standard by the words ‘‘undefined behavior’’ or by the omission of any explicit definition of behavior.[...]

我们也可以查看C99 rationale其中说:

The set of characters required to be preserved in text stream I/O are those needed for writing C programs; the intent is that the Standard should permit a C translator to be written in a maximally portable fashion. Control characters such as backspace are not required for this purpose, so their handling in text streams is not mandated.

关于c++ - cout << "\n"[a==N] 是什么意思?做?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30888851/

相关文章:

c++ - 从像素标签创建 RGB 图像

c++ - 在 Ubuntu 14.04 中启动我的应用程序时出现非法指令(核心转储)错误,如何查看转储

c++ - GCC 的 __builtin_expect 能走多远?

c++ - 带有 boost::any 的 cout 映射

c++ - 使用 std::wcout 会降低奇怪的性能

string - 如何从 Rust 中的文字创建格式化字符串?

c++ - 用嵌入式私有(private)类覆盖 Qt 类

c++ - cout怎么知道如何格式化不同的类型呢?

c - 这真的是缓冲区溢出吗?

syntax - OCaml 的替代字符串语法 {|...|} 在哪里记录?