Difference between char in C and C++?

Viewed 190

I know that C and C++ are different languages.

Code - C

#include <stdio.h>

int main()
{
    printf("%zu",sizeof('a'));
    return 0;
}

Output

4

Code- C++

#include <iostream>
int main()
{
    std::cout<<sizeof('a');
    return 0;
}

Output

1

https://stackoverflow.com/a/14822074/11862989 in this answer user Kerrek SB(438k Rep.) telling about types in C++ nor mentions char neither int but just integral.

is char in C++ is integral type or strict char type ?

3 Answers

is char in C++ is integral type or strict char type ?

Usage of type_traits lets you know the type:

#include <iostream>
#include <type_traits>
int main()
{
    std::cout << std::is_integral<char>();
}

Output:

1

is char in C++ is integral type or strict char type ?

Character types, such as char, are integral types in C++.

The type of narrow character constant in C is int, while the type of narrow character literal in C++ is char.

As others mentioned, In C 'a' is char constant and treated as an integer. In C++ it is integral.

Also you can check the difference between char c = 'a' and 'a' in C++ by using RTTI (run time type info) as follows:

#include <iostream>
#include <typeinfo>
using namespace std;
  
int main()
{

    char c = 'a';
  
    // Get the type info using typeid operator
    const type_info& ti2 = typeid('a');
    const type_info& ti3 = typeid(c);
  

    // Check if both types are same
    if (ti2 != ti3)
        cout << "different type" << endl;
    else
        cout << "same type"<< endl;
  
    return 0;
}

The output is : same type.

However, char c = 'a' and 'a' are NOT same in C.

Related