3

Using XCode 3.2.3 (64-bit), I get following strange output. What am I doing wrong?

#include <iostream>
#include <typeinfo>

struct student {

};

int main()  
{  
    int i;
    student obj;

    std::cout << typeid(i).name() << "\n";
    std::cout << typeid(obj).name() << "\n";

    return 0;
}

Output:

i  
7student
templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
Mahesh
  • 34,573
  • 20
  • 89
  • 115
  • You say it is wrong - what do you expect to see? – mmmmmm Jan 10 '11 at 00:04
  • type of the passing parameter to `typeid` as output. ie `int student` http://stackoverflow.com/questions/81870/print-variable-type-in-c – Mahesh Jan 10 '11 at 00:10
  • possible duplicate of [Why typeid.name() returns weird characters using gcc?](http://stackoverflow.com/questions/4465872/why-typeid-name-returns-weird-characters-using-gcc) – Martin York Jan 10 '11 at 00:57

2 Answers2

8

The name() member function of the type_info struct is implementation-specific. There's no guarantee whatsoever that it will try to return something that matches what it says in the original program. In fact, the C++ ISO standard (18.5.1.7) actually says that this function returns "an implementation-defined NTBS" (null-terminated byte string). If it wanted to, it could have this always return the string "neener neerer I won't tell you the name of this type." This contrasts with Java's Class<?> type, which has very strict restrictions on what it can and cannot return.

If you’d like to convert the name from std::type_info into something more human, readable, check this other question for details.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
4

What's going on is nothing special. Just that typeid doesn't promise to return the "original" name of the type, but just a name.

The function returns an implementation-defined string, which, if you're lucky, is recognizable, but it makes no promise of that.

jalf
  • 243,077
  • 51
  • 345
  • 550