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; }

27th Aug 2018, 12:37 PM
sanket charanpahadi
sanket charanpahadi - avatar
9 Réponses
+ 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
27th Aug 2018, 12:49 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 2
thanks for the support Ketan Lalcheta
27th Aug 2018, 1:02 PM
sanket charanpahadi
sanket charanpahadi - avatar
+ 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
27th Aug 2018, 12:54 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 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
27th Aug 2018, 1:00 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
happy learning...
27th Aug 2018, 1:04 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
please anyone can answer this Deepika Thakur Armita Valizadeh Shruti Sharma anyone!!!
27th Aug 2018, 12:43 PM
sanket charanpahadi
sanket charanpahadi - avatar
0
sanket charanpahadi check in playground once
27th Aug 2018, 12:46 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Ketan Lalcheta I have checked but there are 5-6 errors shown in the code
27th Aug 2018, 12:49 PM
sanket charanpahadi
sanket charanpahadi - avatar