سؤال

I have function:

 void func(unsigned int event) {
       printf("%u %u\r\n", typeid(event), typeid(unsigned int&));
    // prints 5338164 0
       printf("%u %u\r\n", typeid(event), typeid(unsigned int));
    // prints 21525556 0
}

Assume this question is RTFM-related, but i reread typeid() man page several times and could not find an answer. What is wrong with this code? Why %u's is not equal? also why it changes first %u when I changed 2nd param in code. Thanks.

هل كانت مفيدة؟

المحلول

Try

printf("%s %s\n", typeid(event).name(), typeid(unsigned int).name());

As previous replies said, the result of typeid() is opaque and cannot be printed as if it was an int. The fact that this code compiles is just a result of C's bad typing.

نصائح أخرى

So typeid returns a std::type_info not an unsigned int. This appears to compile in Visual Studio but it is not clear what the result means. This code does not compile in either gcc nor clang.

It is undefined behavior to use the wrong format specifier for printf so the behavior is really unpredictable. Visual Studio does not have to produce a warning for this but doing so would be help prevent problems like this. Since std::type_info is not a trivial class do it is implementation defined behavior to use in a variadic function, clang produces this warning:

error: cannot pass non-trivial object of type 'const std::type_info' to variadic function; expected type from format string was 'unsigned int' [-Wnon-pod-varargs]
 printf("%u %u\r\n", typeid(event), typeid(unsigned int));
         ~~  

Using std::type_info::name which returns a const char will give the result you expect:

 printf("%s %s\n", typeid(event).name(), typeid(unsigned int&).name());

and the result from Visual Studio:

unsigned int unsigned int
unsigned int unsigned int
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top