源代码末尾换行

发布于 2024-11-17 20:41:41 字数 316 浏览 4 评论 0原文

每当我在 Visual Studio 中打开代码编辑器时,生成的代码末尾总是有一个空的新行。我通常会删除它们,因为它们似乎与我无关。但是,最近我在 Github 上面写着:

\ No newline at end of file

这是最后一行。现在我认为源代码末尾的那些空新行确实有一些相关性。但它们是什么意思呢?它们是否提供任何性能提升?

Anytime I open up the code editor in Visual Studio, there is always an empty new line at the end of generated codes. I usually delete them since they seem irrelevant to me. However, recently I read code at Github which said:

\ No newline at end of file

This was the last line. Now I'm thinking those empty new lines at the end of source codes do have some relevance. But what do they mean? Do they provide any performance boost?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

为人所爱 2024-11-24 20:41:41

有两件事让我更喜欢在文件末尾添加换行符:

  1. 在查看文件末尾发生的差异时,代码审查会稍微容易一些(即,如果在文件末尾添加一行,则看起来前一行已更改,当它仅获得换行符时)
  2. 转到文件末尾(Windows 中的 Ctrl+End)总是使我位于同一列,而不是位于右侧的某个意外位置

Two things make me prefer having a newline at the end of files:

  1. Code reviews are slightly easier when looking at diffs that occur at the end of the file (i.e., if a line is added at the end of the file, it appears that the previous line changed, when it only gained a newline)
  2. Going to the end of the file (Ctrl+End in Windows) always puts me at the same column and not in some unexpected position out to the right
锦爱 2024-11-24 20:41:41

几乎唯一的区别是,如果你有一个没有换行符的文件 - 就像这样:

blah\n
bleh (no newline)

当你将其修改为:

blah\n
bleh\n
foo (no newline)

然后根据差异,你修改了 2 行 - 一行包含内容,另一行包含换行符..这可能不是你想要的。话又说回来,实际上,你选择哪种方式并不重要。如果您包含换行符,您的差异会更干净一些。

正如其他答案中提到的,它对于某些预处理器也有影响 - 但这取决于您使用的语言。

当然,它根本没有性能差异。

Pretty much the only difference it makes is that if you have a file with no newline - like this:

blah\n
bleh (no newline)

When you modify it to be:

blah\n
bleh\n
foo (no newline)

Then according to the diff, you modified 2 lines - one with content, the other one with newline... which is not what you wanted probably. Then again, in reality it doesn't matter that much which way you choose. If you include newlines, your diffs will be a little bit cleaner.

It also makes difference for some preprocessors as mentioned in other answer - but that depends on what language you use.

Of course it makes no performance difference at all.

与往事干杯 2024-11-24 20:41:41

不,这没有任何区别。

有些编码约定说最好有最后一个换行符,有些则说最好不使用换行符。

No, it makes no difference whatsoever.

Some coding conventions say it's good to have a final newline, some say it's good not to.

慵挽 2024-11-24 20:41:41

在此处阅读有关 C++ 中换行符的更多信息:"文件结尾处没有换行符“编译器警告

我认为 Visual Studio 和 Git 这样做主要是为了与约定保持一致。

Read more about new line in C++ here: "No newline at end of file" compiler warning

I suppose both Visual Studio and Git do it mostly for being coherent with the convention.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文