Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why typeid returns that int and const int are same types

Tags:

c++

typeid

if(typeid(int) == typeid(const int))
       cout << "Same types"<< endl;

PROGRAM OUTPUT:

Same types

am I missing something? these are not same types lol.

like image 627
codekiddy Avatar asked Jan 17 '12 02:01

codekiddy


People also ask

Is const int the same as int const?

const int * And int const * are the same. const int * const And int const * const are the same. If you ever face confusion in reading such symbols, remember the Spiral rule: Start from the name of the variable and move clockwise to the next pointer or type.

What does Typeid return in C++?

The typeid operator returns an lvalue of type const std::type_info that represents the type of expression expr. You must include the standard template library header <typeinfo> to use the typeid operator. Classes A and B are polymorphic; classes C and D are not.

What is the use of Typeid () function?

The typeid operator allows the type of an object to be determined at run time. The result of typeid is a const type_info& . The value is a reference to a type_info object that represents either the type-id or the type of the expression, depending on which form of typeid is used.

What is meant by const int?

int const* is pointer to constant integer This means that the variable being declared is a pointer, pointing to a constant integer. Effectively, this implies that the pointer is pointing to a value that shouldn't be changed.


2 Answers

They aren't the same type, but the typeid operator strips const and volatile.

From section 5.2.8 [expr.typeid]:

The top-level cv-qualifiers of the glvalue expression or the type-id that is the operand of typeid are always ignored.

like image 162
Ben Voigt Avatar answered Sep 21 '22 00:09

Ben Voigt


You probably want this instead:

#include <type_traits>

if (std::is_same<int, const int>::value)
    std::cout << "same types\n";
else
    std::cout << "different types\n";
like image 30
fredoverflow Avatar answered Sep 20 '22 00:09

fredoverflow