Notes on the char data type in C


Single character only, like ‘a’ or ‘0’ with the exception of escape characters such as ‘\n’, ‘\r’ or ‘\t’. Single character constants (chars) must use single quotation marks for their declaration.


char myChar     = 'a';
char myChar2    = ';';
char myChar3    = '0';
char myChar4    = '\n';
printf("Value of myChar is: %c \n", myChar);
printf("Value of myChar2 is: %c \n", myChar2);
printf("Value of myChar3 is: %c \n", myChar3);
printf("Value of myChar4 is: %c \n", myChar4);

Technically chars are integers. Just with a narrower range.

Usually the range will be 1 byte (8 bits). This is because 1 byte allows for 2^8 unique combinations (256). And there are 256 ASCII characters ( Therefore each character can fit into a single byte. This means that there isn’t a need for an extra byte.

You can test the range like so:

printf("On this machine, char is stored in %lu bytes. (%lu bits wide).\n",
           ((sizeof(char)) * 8));

You can also declare chars using their decimal, hexidecimal, octal or binary* equivalents.

The code example below represents the tilde constant (see the ASCII table @

char charSymbol = '~';
printf("Value of charSymbol is: %c \n", charSymbol); // outputs ~

char charDec = 126;
printf("Value of charDec is: %c \n", charDec); // outputs ~

char charHex = 0x7E;
printf("Value of charHex is: %c \n", charHex); // outputs ~

char charOct = 0176;
printf("Value of charOct is: %c \n", charOct); // outputs ~

char charBin =  0b01111110;
printf("Value of charBin is: %c \n", charBin); // outputs ~

All of which are identical.

*Standard C does not support binary constants like 0b01111110; that’s a gcc extension.

You can also test a variable’s rvalue against the decimal, hex, oct or binary values.

char c;
printf("Enter a letter:\n");
scanf("%c", &c);
char tilde = 0x7E;
if (c == tilde){
    printf("you entered a tilde!\n");

Why single quotation marks only?

In C (and in C++) single quotes identify a single character (char), while double quotes create a [string literal]( ‘a’ is a single a character literal (char), while “a” is a string literal containing an ‘a’ and a null terminator (effectively a 2 char array).

Leave a Reply

Your email address will not be published. Required fields are marked *