C Programming

How to Find Size of character (‘a’) in C/C++

The size of a character (a) in C/C++ is an important factor for any program. Although most operating systems use 4 bytes for a character, that may not be the case for your code. Therefore, it is important to check the size of a character to make sure that your code is correctly optimized for the right platform and operating system.

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:

int size = sizeof(char);
#include <iostream>
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.

#include <stdio.h>
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.

About the author

Hiba Shafqat

I am a Computer Science student and a committed technical writer by choice. It is a great pleasure to share my knowledge with the world in which I have academic expertise.