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
?
Note: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
Aucun commentaire:
Enregistrer un commentaire