C++ - Differences Between `unsigned` and `unsigned int` Data Type

During a discussion last week, I've made a mistake when discussing the `unsigned` data type with an acquaintance (not from programming background). Basically, I've misinformed him that `unsigned` is not a data type and it should be `unsigned int` instead. The truth is, in C++, `unsigned` is a data type, implicitly is an alias to `unsigned int`.

To illustrate this, let's use the below code, through typeid operator to determine the data type at runtime, a C++ mechanism called Real-time Type Information (RTTI).
#include <iostream>
#include <typeinfo>

using namespace std;

int main() {
    unsigned int x = 10;
    unsigned y = 20;
    cout << typeid(x).name() << endl;
    cout << typeid(y).name() << endl;

Compile and run the code. Observe that the output shows two js? Because in GCC, the return name is a decorated name (which have been mangled) and we need to demangle it.
$ g++ typeid.cc -o typeid
$ ./typeid

To demangle the name, use the c++filt program, result as shown below. Now the question here is why the function name was mangled? As C++ supports function overloading, a feature where you can define two or more functions/methods with the same name but different function parameters. Conversion to the assembly code needs unique assembler name for these functions. This is where the process of mangling comes in. The c++filt tool reverses the process to find the exact name.
$ ./typeid | c++filt -t
unsigned int
unsigned int

Lots of new things learned here but most importantly, always double check (google in this sense) for any assumed knowledge before you shared with someone else.

No comments:

Post a Comment