Tuesday 11 August 2009

Functions returning void

C++ truths discusses an interesting interview question:

"Can you write a return statement in a function that returns void?" The answer is "Yes! You can return void!"

The following is a simple program picked up from the same blog and modified showing a function returning void



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This is a simple example of a function returning void
#include<iostream>

using namespace
std;

static
void foo (void)
{

cout<<"foo() called"<<endl;
}

static
void bar (void)
{

cout<<"bar() called"<<endl;
return
foo(); // Note this return statement.
}
int
main ()
{

cout<<"main() called"<<endl;
bar();
return
0;
}


The output is as follows:

This feature is very useful in case of Templates. Lets write a simple program that uses Templates:


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This is a simple example of a Template returning void
#include<iostream>
//#include <typeinfo> - Some compilers may need this

using namespace
std;

template
<class T> T FOO (void)
{

cout<<"T FOO() called with T = "<<typeid(T).name()<<endl;
return
T(); // Default construction
}

template
<class T> T BAR (void)
{

cout<<"T BAR() called with T = "<<typeid(T).name()<<endl;
return
FOO<T>(); // Syntactic consistency. Same for int, void and everything else.
}

int
main (void)
{

cout<<"main() called"<<endl;
BAR<void>();
BAR<int>();
BAR<char>();
}



The output is as follows:

No comments:

Post a Comment