Functions

Functions:

pass by value, pass by reference, default arguments, global variables, static variables

Global variables

#include <iostream>
using namespace std;

int g=0; //global var declared outside any function

void foo(){
    int g=1;
    cout<<"global g "<<::g<<endl; // 0 :: scope resolution operator
    cout<<"local  g "<<g<<endl;   // 1
}

void boo(){
    cout<<g<<endl; // 0 global
}

int main(){
    foo();
    boo();
    cout<<"in main "<<g<<endl; // 0 global
    return 0;
}

Static Variables

#include <iostream>
using namespace std;

int foo(){
    static int s=0; //static var value is stored even after function exits
    return ++s; //increment first then return vs s++ (return first then increment)
}

int main(){
    for (int x=0; x<5; ++x)
    {
        cout<<foo(); //12345
    }
    return 0;
}