Functions and scope

These are notes for 11 November.

scope.cpp

#include <iostream>
using namespace std;
// Scope of variables
// The "SCOPE" of a variable is the portion 
// of the program in which that variable is
// visible, or can be accessed.

// GLOBAL variable is defined outside of any function.
int MAXIMUM = 99;

// x and y are both variables, but they're different
// kinds.
void hello(int x)  // x is a PARAMETER,
{                  // gets its value from call site.
    int y = 0;     // y is a LOCAL variable.
    //int x = 9; // shadows the parameter called x
    // .........
    // There are 2 variables in scope here: x, y.
}

int main()
{
    int x = 5;  // local variable in main
    hello(9); // That value gets copied into hello's x
    // Each set of curly braces (a block) introduces
    // a new scope.
    {
        int x = 8;
        x++;
        cout << x << "\n"; // 9
        // scope of INNER x.
    }
    // scope of OUTER x
    x++;
    cout << x << "\n"; // 6;
}

scope2.cpp

#include <iostream>
using namespace std;

int flub(int x)
{
    return 2*x + 1;
}

void showDate(int day, int month) // Parameters get their values
{                                 // from the CALL SITE.
    cout << month << "/" << day << "\n";
}

int main()
{
    int x = 5;
    int y = 8;
    cout << flub(x) << "\n";
    cout << flub(y) << "\n";
    showDate(9, 11);
    return 0;
}

primes.cpp

// prime numbers.
#include <iostream>
using namespace std;

// Determines whether x is a prime number.
bool is_prime(int x)
{
    for(int k = 2; k < x; k++) // k: potential divisors
    {
        if(x % k == 0) // YES I found a divisor
            return false;
    }
    return true;
}

bool twin_prime(int x)
{
    return is_prime(x) && is_prime(x+2);
}

int main()
{
    for(int i = 1; i <= 2000000000; i++)
    {
        if(twin_prime(i))
        {
            cout << "twins: " << i << ", " << i+2 << "\n";
        }
    }
    return 0;
}