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

What is the size of character in C and C++ ? As far as I know the size of char is 1 byte in both C and C++.

In C:

#include <stdio.h>
int main()
{
    printf("Size of char : %d\n", sizeof(char));
    return 0;
}

In C++:

#include <iostream>
int main()
{
    std::cout << "Size of char : " << sizeof(char) << "\n";
    return 0;
}

No surprises, both of them gives the output : Size of char : 1

Now we know that characters are represented as 'a','b','c','|',… So I just modified the above codes to these:

In C:

#include <stdio.h>
int main()
{
    char a="a";
    printf("Size of char : %d\n", sizeof(a));
    printf("Size of char : %d\n", sizeof('a'));
    return 0;
}

Output:

Size of char : 1
Size of char : 4

In C++:

#include <iostream>
int main()
{
    char a="a";
    std::cout << "Size of char : " << sizeof(a) << "\n";
    std::cout << "Size of char : " << sizeof('a') << "\n";
    return 0;
}

Output:

Size of char : 1
Size of char : 1

Why the sizeof('a') returns different values in C and C++?

4 Answers
4

Leave a Comment