PLEASE EXPLAIN THE OUTPUT OF THIS CODE?? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

PLEASE EXPLAIN THE OUTPUT OF THIS CODE??

https://code.sololearn.com/cCWF0xnKF9TT This code outputs 2324 and I don't understand why. Please be specific in your explanation. Thanks!

30th Apr 2018, 11:49 AM
Jackson Meddows
Jackson Meddows - avatar
2 Answers
+ 2
You have to understand that templates will be expanded to COMPILE TIME... This mean that if you define a template function and use it with 2 types, compiler will create two DIFFERENT functions , one for type... Now, you function has a static variable inside it (that "rember" his value between his calls) that for any call increment itself by one but you must understand that func<int> and func<double> are DIFFERENT functions then either will has different static variabile inside they... On first 2 calls all is like expected (2 and 3 are printed) but on double type call, because its another function, it print another static var (2 in this case because its first time call with double type). Next the int type version to be called again and this print the value of static var inside func with int type (3), incremented by one thats 4
30th Apr 2018, 12:01 PM
KrOW
KrOW - avatar
+ 2
The thing with function templates are that they are not functions themselves but a explanation for compiler to how to create the functions with given template parameters. So even though you have one template for a function, when this code is compiled, you 're going to have *two* different functions that have the same name: void fun(int& x); and void fun(double& x); that are identical in what they do. And with these functions, you're going to have *two* different static ints named i. Static variables kind of act like global variables, you can only define them once even though you call the same function several times. So after the first "static int i = 1;" statement of each function, this line will have no effect (it will mot reset the variable back to 1). First fun<int> call: creates the static int inside and outputs its value increased by one: Outputs 2 Second fun<int> call: does not create the static variable again but adds 1 to its previous value: Outputs 3 First fun<double> call: creates a static variable inside it, because it is a different function and adds 1 to its previous value: Outputs 2 Third fun<int> call: does the same thing the second call does: Outputs 4 That became kinda long but hopefully I told it clearly.
30th Apr 2018, 12:21 PM
Alper Tiryakioğlu
Alper Tiryakioğlu - avatar