4 ms·
> Multi-character constants I asked on SO why C characters use `'` on both ends instead of just one (e.g. why not just `'a` instead of `'a'`?). This seems to h
by chrishill89 3y ago
> Multi-character constants
I asked on SO why C characters use `'` on both ends instead of just one (e.g. why not just `'a` instead of `'a'`?). This seems to have been the biggest reason.
- qsort 3y agoThe main reason for that is practicality. '\n' and '\0' are also characters. You could somehow still parse it, but it would be less clear and possibly need more escaping. Multi-character constants are historical baggage.
- chrishill89 3y agoI don’t see the issue. If it’s a literal character it’s one character; if it’s `\n` or or `\0` then it’s two; if it is an octal escape it’s four; and so on. You have to parse them the same way in a character literal as in a string literal, anyway.
- chrishill89 3y ago> if it is an octal escape it’s four; I just figured out that 1. `\0` and octal numbers share the same prefix 2. Octal numbers can have 1-3 digits (not fixed) So maybe it’s more tricky than I thought.
- _kst_ 3y agoAn octal-escape-sequence is a backslash followed by 1, 2, or 3 octal digits. '\0' is just another octal escape sequence, not a special-case syntax for the null character. "\0", "\00", and "\000" all represent the same value; "\0000" is a string literal containing a null character followed by the digit '0'. Hexadecimal escape sequences can be arbitrarily long. If you need a string containing character 0x12 followed by the digit '3', you can write "\x12" "3".
- chrishill89 3y agoThanks, that makes sense. :)
- dfox 3y ago> Multi-character constants are historical baggage. It is more that it is an implementation detail of some compilers that was then (ab)used by certain platforms.
- Ontonator 3y agoNot relevant to C, of course, but Ruby supports something like this with `?a` being equivalent to `"a"` (both of which are strings, since Ruby doesn’t distinguish strings from characters). From what I’ve seen, it is recommended against in most styles, I assume because it is harder to read for most people.
- djur 3y agoIn older days before Ruby had encoding-aware strings, ?a would return the ASCII integer value of 'a'. It made sense in that context but is now pretty much a quirky fossil.