+ 3

Can someone explain reason for the answer? How the output is 112 ?

#include<iostream> using namespace std; template<class T> void f(T){ static int i=0; cout<<++i; } int main(){ f(1); f(1.0); f(1); } output:- 112 why?

1st Aug 2017, 2:01 AM
Abhijeet Jha
Abhijeet Jha - avatar
4 Respostas
+ 14
two different functions are created. (which never actually use the values passed to them btw) void f(int) void f(float) the output is actually 1, 1, 2 soo the code is calling void f(int) twice and void f(float) once. static keyword in effect makes i sort of like a global and it is never set back to 0 after initialization see: http://www.cprogramming.com/tutorial/statickeyword.html
1st Aug 2017, 2:23 AM
jay
jay - avatar
+ 6
It is not required by the compiler.you might get a warning though
1st Aug 2017, 2:50 AM
jay
jay - avatar
+ 2
Why it gets compiled even though there is no variable in the function parameters("void f(T)")??
1st Aug 2017, 2:39 AM
Abhijeet Jha
Abhijeet Jha - avatar