Exercise 3-9 (static vs local variable inside a function)
Chapter_3 Exercise_3-8 Global | Exercise_3-10 |
Exercise 3-9 TCP1, p. 228
Exercise 3-9. Compile and run Static.cpp. Remove the static keyword from the code, compile and run it again, and explain what happens.
CONTENTS: Static.cpp Local.cpp
Static.cpp TCP1, p. 162 download
// Using a static variable in a function
#include <iostream>
using std::cout;
using std::endl;
void func();
int main()
{
for(int x = 0; x < 10; x++)
{func();}
return 0;
}
void func()
{
static int i = 0; // initialize at first function call
cout << "i = " << ++i << endl;
}
/*
g++ Static.cpp -o Static
./Static
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8
i = 9
i = 10
*/
Note: In Static.cpp, the static variable i is initialized the first time the function func() is called, then it preserves its value between function calls. After each function call, the value is incremented, so i varies between 1 and 10 (after ++i).
Local.cpp download
// Using a local variable in a function
#include <iostream>
using std::cout;
using std::endl;
void func();
int main()
{
for(int x = 0; x < 10; x++)
{func();}
return 0;
}
void func()
{
int i = 0; // initialize at every function call
cout << "i = " << ++i << endl;
}
/*
g++ Local.cpp -o Local
./Local
i = 1
i = 1
i = 1
i = 1
i = 1
i = 1
i = 1
i = 1
i = 1
i = 1
*/
Note: Compared to Static.cpp, Local.cpp uses a local variable inside the function func(). Its value is not preserved between function calls. At the beginning of each function call, i is initialized to 0, its value is incremented and printed. The result is printing i = 1 ten times.
Chapter_3 Exercise_3-8 Global | BACK_TO_TOP | Exercise_3-10 |
Comments
Post a Comment