为什么允许字符串文字串联起来? [英] Why allow concatenation of string literals?

查看:97
本文介绍了为什么允许字符串文字串联起来?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近被一个微妙的错误咬伤。

I was recently bitten by a subtle bug.

char ** int2str = {
   "zero", // 0
   "one",  // 1
   "two"   // 2
   "three",// 3
   nullptr };

assert( int2str[1] == std::string("one") ); // passes
assert( int2str[2] == std::string("two") ); // fails

如果您有神圣的code审查的权利,你会发现我忘了两节

If you have godlike code review powers you'll notice I forgot the , after "two".

在相当大的努力来发现错误,我得问问后的为什么会有人曾经想这种行为?

After the considerable effort to find that bug I've got to ask why would anyone ever want this behavior?

我可以看到,这可能是宏观魔术是有用的,但为什么这是一个现代的语言如Python中的功能?

I can see how this might be useful for macro magic, but then why is this a "feature" in a modern language like python?

您是否曾经使用字符串拼接生产code?

Have you ever used string literal concatenation in production code?

推荐答案

我看到几个的 C 的和的 C ++ 的回答没有,但真正回答的为什么还是真的什么是此功能的原因是什么?在 C ++ 的这个功能来自的 C99 的,我们可以去的理由国际标准的编程语言-C 部分 6.4.5 字符串字面的它说(的重点煤矿的):

I see several C and C++ answers but none of the really answer why or really what was the rationale for this feature? In C++ this is feature comes from C99 and we can find the rationale for this feature by going to Rationale for International Standard—Programming Languages—C section 6.4.5 String literals which says (emphasis mine):

一个字符串,可以在多行用反斜杠换行续行继续,但是这需要该字符串的延续,在未来行的第一个位置开始。 要允许更多的灵活的布局,并解决了一些preprocessing问题(见§6.10.3),该委员会C89引入了字符串串联。在连续两个字符串文字粘贴在一起,在中间没有空字符,使一个组合的字符串。这除了C语言的允许程序员扩展字符串超出了物理行的结尾,而不必使用反斜杠换行机制并从而破坏程序的缩进方案。 并没有出台一个明确的连接符,因为串联是一个词法结构,而不是运行时操作。

A string can be continued across multiple lines by using the backslash–newline line continuation, but this requires that the continuation of the string start in the first position of the next line. To permit more flexible layout, and to solve some preprocessing problems (see §6.10.3), the C89 Committee introduced string literal concatenation. Two string literals in a row are pasted together, with no null character in the middle, to make one combined string literal. This addition to the C language allows a programmer to extend a string literal beyond the end of a physical line without having to use the backslash–newline mechanism and thereby destroying the indentation scheme of the program. An explicit concatenation operator was not introduced because the concatenation is a lexical construct rather than a run-time operation.

的Python 的似乎有同样的原因,这样可减少\\ 需要难看的继续长字符串。这是覆盖在部分 2.4.2字符串文字串联
Python语言参考

Python which seems to have the same reason, this reduces the need for ugly \ to continue long string literals. Which is covered in section 2.4.2 String literal concatenation of the The Python Language Reference.

这篇关于为什么允许字符串文字串联起来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆