The first step to check the size of a character in C/C++ is to use the sizeof operator. This operator will tell you the exact size in bytes of the data type that is given as an argument.
How to Find Size of a Character in C++
So, if we wanted to check the size of a single character in C++, we would use this snippet of code:
using namespace std;
int main()
{
int size1= sizeof(char);
int size = sizeof('a');
cout >> "size of the character a is: ">>size;
cout >> "\nsize of a character is: ">>size1;
}
In this code, the size of a character, and the size of a character ‘a’ is found out using the sizeof operator. And the sizes of the characters are printed using cout statements which are 1.
Output
Size of a Character in C
In order to calculate the sizes of data types or expressions that are defined in char-size storage units, we often utilize the sizeof() operator in the C language. A cast data type or an expression can be used as the only operand for the sizeof() operator. In this case, a data type wrapped in parentheses in the program is referred to as the cast.
int main()
{
char a = 'a';
printf("Size of char a : %d\n", sizeof(a));
printf("Size of char 'a' : %d\n", sizeof('a'));
return 0;
}
In the above code, a character is declared and initialized under variables ‘a’, and the size of ‘a’ is then found using the sizeof() function and printed on the screen.
Output
This will return the size of the character in bytes. In C, a character constant like ‘a’ really has the type of an int and has a size of 4.
However, the sizeof operator is limited in what data types it can check. It’s limited to only built-in types such as int, float, char, and so on.
Conclusion
Checking the size of a character in C/C++ can be done in a few different ways. The simplest approach is to use the sizeof operator, which can be used to determine an array’s size or the number of items it contains. However, to check a character that has been user-defined, such as a structure or class, a different approach is needed.