Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static variable used in a template function

Tags:

c++

oop

templates

I am not able to understand the output of the below code:-

#include <iostream>
using namespace std;
template <typename T>
void fun(const T&x){
 static int count = 0;
 cout << "x = " << x << " count = " << count << endl;
 ++count;
 return;
}
int main(){
 fun(1);
 fun('A');
 fun(1.1);
 fun(2.2);
 return 0;
}
Output:-
x = 1 count = 0
x = A count = 0
x = 1.1 count = 0
x = 2.2 count = 1

If value of static variable count is being reassigned to 0 whenever the function is called, then why its coming 1 when the function is being called fourth time. And another thing , can we not pass "T x" directly instead of "const T&x"?

like image 247
Rishabh Gupta Avatar asked Dec 14 '22 07:12

Rishabh Gupta


2 Answers

When a template gets instantiated, with explicit or deduced template parameters, it's as if a completely new, discrete, class or function gets declared. In your case, this template ends up creating three functions:

void fun<int>(const int &x)

void fun<char>(const char &x)

void fun<double>(const double &x)

It's important to understand that each one of these is a separate, standalone function, with its own static count variable. Because it's static, it gets initialized once, and its value is preserved across function calls. That's how static variables work in functions.

The shown code calls the first two once, and the third one twice. Those are the results you are seeing (the 2nd call to the third function incremented the same static count again).

like image 132
Sam Varshavchik Avatar answered Jan 01 '23 07:01

Sam Varshavchik


Templates in C++ aren't generic functions like they are in Java. They're more like cookie cutters that make a new type-specific function for each type used to instantiate them. Your code is basically equivalent to this:

#include <iostream>
using namespace std;
void fun_int(const int&x){
 static int count = 0;
 cout << "x = " << x << " count = " << count << endl;
 ++count;
 return;
}
void fun_char(const char&x){
 static int count = 0;
 cout << "x = " << x << " count = " << count << endl;
 ++count;
 return;
}
void fun_double(const double&x){
 static int count = 0;
 cout << "x = " << x << " count = " << count << endl;
 ++count;
 return;
}
int main(){
 fun_int(1);
 fun_char('A');
 fun_double(1.1);
 fun_double(2.2);
 return 0;
}

And now it's obvious that you don't just have one static variable, but rather three different ones in different functions that just happen to have the same name.

like image 38
Joseph Sible-Reinstate Monica Avatar answered Jan 01 '23 07:01

Joseph Sible-Reinstate Monica