Question

I was writing some code in C# the other day and it got me thinking. If a char literal can only have 1 char (or a delimited character) then why do we need the closing delimiter?

For example, currently we need to write:

char character = 's';

And there is no circumstance where this can work (obviously):

char character = 'sa';

Then why do we have to put the closing ' rather than have it implied? Eg:

char character = 's;
char anotherCharacter = '\';

Readability would only be impacted because we are used to the current standard (not necessarily because this way is less readable).

Was it helpful?

Solution 2

In C#, Java and C++ the answer is simple:

Because that's the way it was implemented in C.

Why was it implemented in C that way?

Who knows? There may be some implementation quirk in the first C parser/compiler that made this choice obvious; I'm betting that K&R just didn't think about it. A single quote just looks weird.

OTHER TIPS

  1. It's a convention
  2. Characters are not necessarily represented in one character, in this unicode world
  3. Control / escape sequences can be longer than one character (e.g. '\0x1a' )

'abcd' is a multi-character literal; it's type is int, and its value is implementation defined. The closing ' is needed to mark the end of the literal.

The existing C syntax defines character-constant as:

character-constant:

' c-char-sequence '

L' c-char-sequence '

Your question boils down to why this couldn't be defined instead as:

character-constant:

' c-char

L' c-char

Well, it could - in the sense that this would still be a consistent parseable grammar, and you'd still be able to express single-character constants. What you couldn't do is express multiple-character constants (eg. 'ab') - these are legal, but have a value that is implementation-defined.

I suspect that the true reason is simply aesthetics. For example, there's also no reason in theory why parantheses are needed around the conditional expression of an if statement either.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top