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 lettersu
,u
orL
, as inu'y'
,U'z'
orL'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.
source to share
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?
source to share