How to get the data type of a variable in C++

2 Answers

0 votes
#include <iostream>
#include <typeinfo>

int main() {
    int age = 25;
    double pi = 3.14159;
    std::string name = "Alice";

    // typeid().name() returns a implementation-dependent string
    std::cout << "age type: " << typeid(age).name() << '\n';
    std::cout << "pi type: " << typeid(pi).name() << '\n';
    std::cout << "name type: " << typeid(name).name() << '\n';
}


/*
run:

age type: i
pi type: d
name type: NSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE

*/

 



answered 1 day ago by avibootz
0 votes
#include <iostream>
#include <type_traits>

int main() {
    int x = 10;
    
    // decltype(x) evaluates to 'int'
    decltype(x) y = 20; // y is an int

    // You can check the type at compile-time using std::is_same_v
    if constexpr (std::is_same_v<decltype(y), int>) {
        std::cout << "y is an integer!\n";
    }
}


/*
run:

y is an integer!

*/

 



answered 1 day ago by avibootz
...