Tuesday 2 February 2016

How to know the type of en expression at run-time of a C++ program?

Most of us know that how to get the type of variable in C++ at compile time.
Example:
#include<iostream>
#include<typeinfo>
int main()
{
    int var = 10;
    std::cout<<"\n The type of the variable var is "<<typeid(var).name()<<std::endl;
    return 0;
}

Output:
The type of the variable var is i
i represents integer.

Now suppose we have a program like this :
#include<iostream>
#include<typeinfo>
int main()
{
    int var;
    std::cin>>var;
    std::cout<<typeid(5.0/var).name()<<std::endl;
    return 0;
}
Now suppose that you give the input as 5. Then you might except the output to be i. But this will not happen and the output for any input here will be d (d for decimal).

Okay then what is the reason behind this?
The answer is that typeid only tells you about the static type determined at compile-time. The expression we have written is always floating-point.

To know that what is the type of the expression we don't have any predefined function in C++ however this can be done easily in programming language like python, ruby.
To know the type whether the expression is decimal or integer we can evaluate the expression and store it into a float type variable. And again you store the same evaluated expression into an integer type variable. Now if you subtract the integer type variable with the floating type variable you will get the decimal value.
If that subtracted value is 0 then we can easily say that the expression has integer value otherwise it must be a float.

So the above program can be written like.
#include<iostream>
#include<typeinfo>
int main()
{
    int var;
    std::cin>>var;
    int a = 5.0/var;
    float b = 5.0/var;
    if(b-a == 0)
        std::cout<<"\n integer";
    else
        std::cout<<"\n decimal";
    return 0;
}
Now this will be a perfect way to know the type of the expression at run-time of a program. Well there are many more methods you can think of.

No comments:

Post a Comment