I'm a beginner programmer...Here I have a piece of code with two functions...one of them uses a global variable while the other one uses a local static variable...
So here is the code:
//Scope Rules
#include <iostream>
using namespace std;
int num {52}; //Global Variable - Declared outside any class or function
void globalExample();
void staticLocalExample();
void globalExample(){
cout << "\nGlobal num in globalExample is: " << num << " - start" << endl;
num *= 4;
cout << "Global num in globalExample is: " << num << " - end" << endl;
}
void staticLocalExample(){
static int num {5}; //local to staticLocalExample - retains it's value between calls
cout << "\nLocal static num in staticLocalExample is: " << num << " - start" << endl;
num += 20;
cout << "Local static num in staticLocalExample is: " << num << " - end" << endl;
}
int main() {
globalExample();
globalExample();
staticLocalExample();
staticLocalExample();
return 0;
}
The reason I called these functions twice was for me to understand that the second time the function is called, changes will be stored to the variables so the results will be different.
What I don't understand is:
- What's the difference between these two functions then?
- What does the
staticLocalExample
function exactly do?(Because in comparison, they both have the same results) - Why and when do we use the keyword
static
?
Note1:I know the cause of changes is the assignments I have in both functions BUT... This is just an example and I don't quietly understand it
Note2:I checked the link you guys sent me and thank you so much for that...I understood the concepts behind it but still I couldn't find the answer to my third question :)