0
What is the output of this code? Please help!!!!
Template<typename T> void fun(const T& x) { static int i=1; cout<<++i; return; int main () { fun<int>(1); fun<int>(2); fun<double>(1); fun<int>(4); return 0; }
9 Answers
+ 2
sanket charanpahadi it has minor error or typo..updated code is below:
#include <iostream>
using namespace std;
template<typename T>
void fun(const T& x) {
static int i=1;
cout<<++i;
return;
}
int main ()
{
fun<int>(1);
fun<int>(2);
fun<double>(1);
fun<int>(4);
return 0;
}
output is 2324
+ 2
thanks for the support
Ketan Lalcheta
+ 1
template function fun is called for two data types.... int and double... for int datatype, it will be called for 1 2 and 4 where as for double, it will be called for value 1...
now coming to function execution, static int i = 1 is executed only once as static variable values are initialised only once...
so, it gets executed for int 1 and double 1.so, ++i results into 2 for both... for 2 nd 3 of int, ++i is 3 and 4 respectively
+ 1
just remove static from function and output will be 2222...
static makes it to execute only once for each datatype...
if you call another fun for another double value, you will get 3 for that call.. try with new datatype float and again you will get 2 as answer first time for float
+ 1
happy learning...
0
0
sanket charanpahadi check in playground once
0
Ketan Lalcheta I have checked but there are 5-6 errors shown in the code