I want to print out the type of variable.

Asked 1 years ago, Updated 1 years ago, 99 views

In c++, how do you output a variable type?

I checked it using type() in Python, but I am asking because I think there will be such a method in C++. What is the function that functions typeof(a) in the code below?

int a = 12;
cout << typeof(a) << endl;

c++ c++11 type

2022-09-21 17:15

1 Answers

<typeinfo> header has std::type_info::name.

Returns a null-terminated character sequence that may identify the type.

// type_info::name example
#include <iostream>       // std::cout
#include <typeinfo>       // operator typeid

int main() {
  int i;
  int * pi;
  std::cout << "int is: " << typeid(int).name() << '\n';
  std::cout << "  i is: " << typeid(i).name() << '\n';
  std::cout << " pi is: " << typeid(pi).name() << '\n';
  std::cout << "*pi is: " << typeid(*pi).name() << '\n';

  return 0;
}

Output:

int is: int
  i is: int
 pi is: int *
*pi is: int


2022-09-21 17:15

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.