Why can't character constants / literals be empty?

In C and C ++, the rules are the same. In C,

[ยง6.4.4.4]/2

An integer character constant is a sequence of one or more multibyte characters, enclosed in single quotes, as in 'x'

.

In C ++,

[ยง2.14.3]/1

A character literal is one or more characters enclosed in single quotes, as in 'x'

, optionally preceded by one of the letters u

, u

or L

, as in u'y'

, U'z'

or L'x'

, respectively.

The key phrase is "one or more". In contrast, a string literal can be empty, ""

presumably because it consists of a null terminating character. In C, this leads to awkward initialization of a char. Either you leave it uninitialized, or use a useless value like 0

or '\0'

.

char garbage;
char useless = 0;
char useless2 = '\0';

      

In C ++, you need to use a string literal instead of a character literal if you want it to be empty.

(somecondition ? ' ' : '') // error
(somecondition ? " " : "") // necessary

      

What is the reason for this? My guess is the reason C ++ inherits from C.

+3


source to share


3 answers


The reason is that a character literal is defined as a character. There may be extensions that allow more than one character, but it must be at least one character, or it just doesn't make any sense. This will be the same as trying:

int i = ;

      



If you didn't provide a value, what did you put there?

+10


source


This is because the empty string still contains a null character '\0'

at the end, so there is still a value to bind to the variable name, whereas an empty literal letter does not matter.



+3


source


String is a null-terminated character set ('\ 0'). Thus, an empty string will always have a NULL character at the end.

But in the case of a character literal, there is no value. it needs at least one character.

0


source







All Articles