how to know datatype of something in c++
To determine the datatype of something in C++, you can use the typeid
operator or the decltype
keyword. Here's an explanation of each step:
- Using the
typeid
operator: Thetypeid
operator allows you to obtain the type information of an expression or a variable at runtime. It returns atype_info
object that represents the datatype. To usetypeid
, follow these steps: - Include the
<typeinfo>
header at the beginning of your code. - Use the
typeid
operator followed by the expression or variable whose datatype you want to determine. - To get the name of the datatype, call the
name()
member function on thetype_info
object returned bytypeid
.
Here's an example:
```cpp
#include
int main() {
int num = 10;
const std::type_info& type = typeid(num);
std::cout << "Datatype: " << type.name() << std::endl;
return 0;
}
Output:
Datatype: int
```
- Using the
decltype
keyword: Thedecltype
keyword allows you to deduce the datatype of an expression or a variable at compile-time. It returns the exact datatype of the expression or variable. To usedecltype
, follow these steps: - Use the
decltype
keyword followed by the expression or variable whose datatype you want to determine. - Assign the result to a variable of type
std::type_info
to get the name of the datatype.
Here's an example:
```cpp
#include
int main() {
int num = 10;
decltype(num) result;
const std::type_info& type = typeid(result);
std::cout << "Datatype: " << type.name() << std::endl;
return 0;
}
Output:
Datatype: int
```
These methods allow you to determine the datatype of something in C++. Remember to include the necessary headers and use the appropriate syntax for each method.