Reputation: 31
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 the 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 have 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 it is this way? I'm assuming C++'s reason is inherited from C.
Upvotes: 3
Views: 448
Reputation: 441
String is a set of character terminated by a NULL character ( '\0' ). So a Empty string will always have a NULL character in it at the end .
But in case of a character literal no value is there. it needs at least one character.
Upvotes: 0
Reputation: 81
This is because an empty string still contains the the null character '\0'
at the end, so there is still a value to bind to the variable name, whereas an empty character literal has no value.
Upvotes: 3
Reputation: 308206
The reason is that a character literal is defined as a character. There may be extensions that allow it to be more than one character, but it needs to be at least one character or it just doesn't make any sense. It would be the same as trying to do:
int i = ;
If you don't specify a value, what do you put there?
Upvotes: 10