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.
Type | Storage Size |
---|---|
char | 1 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
#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:
- We declare three
char
variables:letter
,digit
, andsymbol
. - We assign the characters
'A'
,'5'
, and'#'
to these variables. - 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
#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:
Type | Minimum Value | Maximum Value |
---|---|---|
signed char | -128 | 127 |
unsigned char | 0 | 255 |
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
#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:
- Its ability to store single characters from the ASCII character set.
- Its fixed storage size of 1 byte (8 bits).
- How to check its storage size programmatically using
sizeof()
. - The minimum and maximum values that
char
can store. - How to retrieve these values using
limits.h
.
The char
data type is essential in C programming, especially for handling characters and text.