字符字面量后面加撇号有什么好处 [英] What's the benefit of the trailing apostrophe in character literals

查看:110
本文介绍了字符字面量后面加撇号有什么好处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写自己的编程语言,并且现在正在重新考虑语法的许多方面.在大多数语言中,很多困扰着我的是字符文字中的尾随撇号.

示例
带有斜杠:'n'
不带斜杠:'n

为什么新语言(例如rust f.e.)继续使用结尾的撇号?
看到此类语言解决了旧语言所遇到的问题(好吧,结尾的撇号并不是真正的问题),让我认为保留结尾的撇号一定有好处.如果它支持可读性,我同意保留它,但我认为它不支持.
这里有一些更奇特的例子:

I am writing my own programming language and am reconsidering many aspects of my syntax right now. Something that bothers me in many most languages is the trailing apostrophe in character literals.

Example
With trailing slash: 'n'
Without trailing slash: 'n

Why do new languages (like rust f.e.) keep using a trailing apostrophe?
Seeing such languages fixing issues we had with old languages (ok, the trailing apostophe is not really an issue) leaves me thinking that there must be a benefit to keeping the trailing apostrophe. I'd agree to keep it if it supports readability, but I don't think it does.
Here are some more exotic examples:

  • '\n  vs  '\n'
  • '\r  vs  '\r'
  • '\t  vs  '\t'
  • '\\  vs  '\\'
  • '\'  vs  '\''
  • '\"  vs  '\"'
  • '\n   vs   '\n'
  • '\r   vs   '\r'
  • '\t   vs   '\t'
  • '\\   vs   '\\'
  • '\'   vs   '\''
  • '\"   vs   '\"'

我们是否出于历史原因保留了这种语法,或者还有我尚不了解的语法?
请注意,必须在字符串文字中尾随引号.

Do we keep this syntax due to historical reasons or is there more to it that I don't yet understand?
Note that the trailing quotation mark in a string literal is necessary.

推荐答案

因为

  1. 您不希望字符文字出现错误来更改程序其余部分的含义.例如,有二合字母和三合字母,因此可能的字符字面量有很大的空间,并且有很多方法可以指定无效的字面量.您不希望无效字符之后的部分成为程序其余部分的一部分,以进行扫描或解析.您想知道在哪里停下来.

  1. You don't want an error in a character literal to change the meaning of the entire rest of the program. There are digraphs and trigraphs for example, so quite a large space of possible character literals and quite a lot of ways to specify an invalid one. You don't want the part after the invalid character to become part of the rest of the program for scanning or parsing purposes. You want to know where to stop.

您真的不希望合法字符字面量规则成为该语言的词法规范的一部分,该语言规范必须极其稳定.您希望能够添加新的有向图,有向图等,而不必重新指定语言的词汇规则,并且无需更改现有程序的含义.

You don't really want the legal character literal rules to be part of the lexical specification of the language, which has to be extremely stable. You want to be able to add a new digraph, trigraph, etc., without having to respecify the lexical rules of the language, and without changing the meaning of existing programs.

这篇关于字符字面量后面加撇号有什么好处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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