Using character constants instead of string literals and vice versa
suggest changeIn C, character constants and string literals are different things.
A character surrounded by single quotes, such as 'a', is a character constant. It has type int. Its value is the character’s code in the execution character set. The value of a multi-character constant such as 'abc' is implementation-defined.
Zero or more characters surrounded by double quotes, such as "abc", are a string literal. The literal is an array of char, including the terminating null character, so "abc" has four elements: 'a', 'b', 'c', and '\0'. Modifying those elements is undefined behavior.
In this example, a character constant is used where a string literal should be used. 'hello, world' has type int. Assigning that int to const char * is a constraint violation, not an implicit conversion. A conforming compiler must diagnose it.
#include <stdio.h>
int main(void) {
const char *hello = 'hello, world'; /* bad */
puts(hello);
return 0;
}
In this example, a string literal is used where a character constant should be used. The literal decays to a pointer. Assigning that pointer to a char is a constraint violation. A conforming compiler must diagnose it. There is no implicit conversion from a pointer to char.
#include <stdio.h>
int main(void) {
char c = "a"; /* bad */
printf("%c\n", c);
return 0;
}
In almost all cases, the compiler will complain about these mix-ups. If it doesn’t, you need to use more compiler warning options, or it is recommended that you use a better compiler.