+ 2

Why is this the output?

I've got this code in C++***: template<class T> void f(T){ static int i = 0; cout << ++i;} int main(){ f(1); f(1.0); f(1);} Why is the output 112 and not 123? Clearly the program does run for f(1.0), because it would've been 12 otherwise, but why doesn't it add 1 then?

9th May 2017, 6:30 PM
Maart
Maart - avatar
2 Respostas
+ 2
first, this is not java code. It is C++. Running the code through gdb shows two different copies of the function f being made each with it's own local copy of i. so for the 1.0 call, you get 1 on output.
9th May 2017, 7:19 PM
Venkatesh Pitta
Venkatesh Pitta - avatar
+ 1
Of course! Thanks!
9th May 2017, 7:23 PM
Maart
Maart - avatar