The char Type
char is C's smallest integer type, guaranteed by the standard to be exactly one byte in size (sizeof(char) is always 1, by definition). It is most often used to store a single character, but under the hood a char is really just a small integer, and it supports arithmetic like any other integer type.
char is a small integer
#include <stdio.h>
int main(void) {
char c = 'A';
printf("%c has code %d\n", c, c);
char next = c + 1; /* arithmetic on a char! */
printf("next character: %c\n", next);
for (char letter = 'a'; letter <= 'e'; letter++) {
printf("%c ", letter);
}
printf("\n");
return 0;
}A has code 65 next character: B a b c d e
signed char vs unsigned char
#include <stdio.h>
int main(void) {
char c = 200; /* out of signed char's positive range */
unsigned char uc = 200;
printf("plain char: %d\n", c); /* implementation-defined result */
printf("unsigned char: %d\n", uc); /* always 200 */
return 0;
}Character literals vs string literals
#include <stdio.h>
int main(void) {
char letter = 'A'; /* one char, value 65 */
const char *word = "A"; /* pointer to a 2-byte array: {'A', '\0'} */
printf("sizeof('A') as used here holds one char\n");
printf("strlen-equivalent length of \"A\" is 1, but it occupies 2 bytes\n");
/* char letter2 = "A"; */ /* INVALID: cannot assign a string to a char */
return 0;
}Form | Type | Size | Example |
|---|---|---|---|
Character literal |
| 1 byte value |
|
String literal | array of | length + 1 for the null terminator |
|
charis guaranteed to be exactly one byte, typically used to store one character.A char is really a small integer — you can perform arithmetic on char values.
Whether plain
charis signed or unsigned is implementation-defined; usesigned char/unsigned charexplicitly when it matters.'A'(single quotes) is a single char value;"A"(double quotes) is a 2-byte array including a null terminator — never confuse the two.