4 ms·
About newlines and string literals: why do languages allow newlines in source code to be part of strings? is there some hidden wisdom behind that? Personally,
by axilmar 6y ago
About newlines and string literals: why do languages allow newlines in source code to be part of strings? is there some hidden wisdom behind that?
Personally, I would expect that the string
"the quick brown fox
jumps over the lazy dog"
Would be like this in runtime:
"the quick brown fox jumps over the lazy dog"
Whereas this:
"the quick brown fox\n
jumps over the lazy dog"
would be like this in runtime:
"the quick brown fox
jumps over the lazy dog"
- sergeykish 6y agoI have same question, it is easy to solve in rich text environment [1]. But it is also possible to solve quotes in quotes. Browser solves it beautifully — we never think how <>& escaped while reading the page, it just works in contenteditable. let encoded = this.textContent.replaceAll("\n", "\\n") .replaceAll('"', '\\"') return `"${encoded}"` [1] http://sergeykish.com/c-multiline-string http://sergeykish.com/c-multiline-string
- int_19h 6y agoThe spaces are already significant in strings, so why not other whitespace? If you try to exclude newlines specifically, it becomes messy when you have to deal with indentation. E.g. how should this parse? foo = "this is a multiline string"; If you simply ignore the newlines, you'll end up with a bunch of spaces. If you start collapsing whitespace, detecting indentation levels etc, parsing becomes a lot more complicated, and harder to explain (which you still need to do, because it won't always "just work").
- axilmar 6y agoThe newline character plays a very important role in formatting source code: long declarations/statements are usually broken up into several lines of code using hidden newlines. These newlines do not alter the meaning of code. The same hidden newlines though in a string will alter the string: they will make the string multiline. So, in order to be more consistent with how code is formatted, I'd prefer hidden newlines in strings to not modify the strings.
- int_19h 6y agoEverything inside the quotes alters the string, so it's quite consistent in that sense. And even in a language where whitespace is completely insignificant, it's not insignificant inside a string literal.