C char Data Type

In C, the char data type is used to store a single character. It is a fundamental data type and is commonly used for character representation and string handling. A char variable can hold any character from the ASCII character set, including letters, digits, symbols, and whitespace characters.


1 Storage Size of char Data Type

The char data type in C requires exactly 1 byte of memory.

TypeStorage Size
char1 byte (8 bits)

Since a char is 1 byte in size, it can store values ranging from -128 to 127 in a signed implementation or 0 to 255 in an unsigned implementation.

2. Values Stored by char Data Type

The char data type stores single characters from the ASCII character set. Each character corresponds to a unique numeric value (ASCII code).

Example values that can be stored in char:

'A', 'z', '9', '#', ' '

3. Example: Declaring and Using char Variables

Let’s see a simple program demonstrating how to declare and use char variables in C.

main.c

</>
Copy
#include <stdio.h>

int main() {
    char letter = 'A';
    char digit = '5';
    char symbol = '#';

    printf("Letter: %c\n", letter);
    printf("Digit: %c\n", digit);
    printf("Symbol: %c\n", symbol);

    return 0;
}

Explanation:

  1. We declare three char variables: letter, digit, and symbol.
  2. We assign the characters 'A', '5', and '#' to these variables.
  3. We use the printf() function to print the values, using the format specifier %c (character format).

Output:

Letter: A
Digit: 5
Symbol: #

4. Checking Storage Size of char Programmatically

We can determine the storage size of char in bytes using the sizeof operator.

main.c

</>
Copy
#include <stdio.h>

int main() {
    printf("Size of char: %lu byte\n", sizeof(char));
    return 0;
}

Output:

Size of char: 1 byte

5. Minimum and Maximum Values of char

The range of values a char can store depends on whether it is signed or unsigned:

TypeMinimum ValueMaximum Value
signed char-128127
unsigned char0255

6. Getting Maximum and Minimum Values of char Programmatically

The maximum and minimum values of a char can be retrieved using limits.h.

main.c

</>
Copy
#include <stdio.h>
#include <limits.h>

int main() {
    printf("Minimum signed char value: %d\n", SCHAR_MIN);
    printf("Maximum signed char value: %d\n", SCHAR_MAX);
    printf("Maximum unsigned char value: %u\n", UCHAR_MAX);
    return 0;
}

Output:

Minimum signed char value: -128
Maximum signed char value: 127
Maximum unsigned char value: 255

Conclusion

In this tutorial, we explored the char data type in C, including:

  1. Its ability to store single characters from the ASCII character set.
  2. Its fixed storage size of 1 byte (8 bits).
  3. How to check its storage size programmatically using sizeof().
  4. The minimum and maximum values that char can store.
  5. How to retrieve these values using limits.h.

The char data type is essential in C programming, especially for handling characters and text.