DEV Community

Cover image for Understand chars in 5 mins or less
Dave Mcsavvy
Dave Mcsavvy

Posted on

Understand chars in 5 mins or less

What is the char type in C and how should it be used.

Before we dive into these, let's have a quick glance at C types.

Types In C

Types are useful to us because they allow us to handle values in a specific way.
In the backend though, C uses types to determine how much memory to allocate for a given value.
C is very particular about memory and it needs to know the type of every value.

The Char type

This special type refers to printable and control character - basically every key on your keyboard!

Declaring Characters

The syntax for declaring a variable as a char looks like this

char character = 'Z';
Enter fullscreen mode Exit fullscreen mode

Note that single quotes '' are used instead of double quotes ""

Under the hood, all char type translate to an integer. So you declare character like this

char c = 48
Enter fullscreen mode Exit fullscreen mode

Or

char c = '0'
Enter fullscreen mode Exit fullscreen mode

You can view the a table of all characters and their integer representation here


Char Operations

C provides a library for handling characters in an exciting way 🔥
You can use that library by including the ctype.h library at the top of your script like this

#include <ctype.h>
Enter fullscreen mode Exit fullscreen mode

Here are a few utilities the library gives you for free...

check is a character is lower case

char c = 'a';

if (islower(c))
    // do something 
Enter fullscreen mode Exit fullscreen mode

islower returns 1 if a character is lower case, and 0 if it's not.

check is a character is upper case

char c = 'A';

if (isupper(c))
    // do something 
Enter fullscreen mode Exit fullscreen mode

isupper returns 1 if a character is upper case, and 0 if it's not.

check is a character is an alphabet

char c = 'A';

if (isalpha(c))
    // do something 
Enter fullscreen mode Exit fullscreen mode

isalpha returns 1 if a character is an alphabet, and 0 if it's not.

check is a character is a digit

char c = '4';

if (isdigit(c))
    // do something 
Enter fullscreen mode Exit fullscreen mode

isdigit returns 1 if a character is a decimal number, and 0 if it's not.

check is a character is a digit or alphabet

char c = 'y';

if (isalphanum(c))
    // do something 
Enter fullscreen mode Exit fullscreen mode

isalphanum returns 1 if a character is a digit or alphabet, and 0 if it's not.

Bet you can guess what these functions do

  • ispunc

  • isspace

You can also convert characters to uppercase and lowercase using toupper and tolower respectively.

char c = 'A';

// Switch case
if (isupper(c))
    c = tolower(c);
else if (islower(c))
    c = toupper(c));
Enter fullscreen mode Exit fullscreen mode

Spoilers
Emojis are also chars!

char damn = '🥵'
Enter fullscreen mode Exit fullscreen mode

Top comments (0)