Reputation: 22821
I tried this and got the output as: void
Please explain the following Code:
#include <cstdio>
#include <typeinfo>
using namespace std ;
void foo()
{ }
int main(void)
{
printf("%s",
typeid(foo()).name());// Please notice this line, is it same as typeid( ).name() ?
return 0;
}
AFAIK: The typeid operator allows the type of an object to be determined at run time.
So, does this sample code tell us that a function that returns void is of **type void**. I mean a function is a method and has no type. Correct?
Upvotes: 2
Views: 3966
Reputation: 320541
typeid
does not work with objects. It works with expressions.
typeid
returns the type of the expression you supply to it as an argument. The expression can refer to an object, or to something that is not an object. You supplied expression foo()
as an argument. This expression has type void
. So, you got a result that refers to type void
. void
, BTW, is not an object type.
Function do have types. If you want to apply typeid
to the function itself, the syntax would be typeid(foo)
. The function-to-pointer conversion is not applied to the argument of typeid
, which means that you should get a result that refers to function type itself. Meanwhile, typeid(&foo)
will give you a function pointer type id, which is different from typeid(foo)
.
Upvotes: 9
Reputation: 40859
Wrong on both counts.
1) The sample code tells you that the type of the result of calling foo() is void.
2) Functions are also types.
Upvotes: 1
Reputation: 76541
That is telling you the type of the function's return.
To get the type of the function itself, you want:
typeid(foo) // note the lack of ()
Upvotes: 2