Storage classes C++ : Global, Local, Register, Static & Extern

The purpose of Storage classes C++ is used to specify the lifetime and visibility of a variable. The allocation of the variable and how each variable is controlled by the compiler depends on which storage class it uses in the code.

In C++ there are five types of storage classes which are:

  1. Global variables
  2. Local variables
  3. Register variables
  4. Static variables
  5. Extern variables

Global variables

These variables are declared at the start of the program, before all the user created functions and the int main() function. The advantage of this allows the global variables to be accessed anywhere in the code.

using namespace std;
int global_variable; // Global variable
void function(); 
int main() 
{ 
..... 
}

 

Local variables

Local variables are also known as Automatic variables because they are only visible within the function it is declared and its lifetime is same as the lifetime of the function as well. Once the execution of function is finished, the variable is destroyed.  By default all local variables are auto, so we don’t have to explicitly add keyword auto before declaring a local variable. Default value of such variable is garbage.

#include <iostream.h>
int test()
{
  int x;
  x = 200;
  return x;
}

 

Register variables

Stores the variable in the CPU instead of the RAM. Almost similar to a local variable but has the advantage of increasing the access speed and making the program run faster. Register variables can only be declared only within a block, which means you cannot have global or static register variables.

#include <iostream.h>
 
using namespace std;
 
int main()
{
  int num1, num2;
  register int sum;
 
  cout << "\nEnter the Number 1 : ";
  cin >> num1;
 
  cout << "\nEnter the Number 2 : ";
  cin >> num2;
 
  sum = num1 + num2;
 
  cout << "\nSum of Numbers : " << sum;
 
  return 0;
}

 

Static variables

Initialized & allocated storage only once at the beginning of program execution. It can be used only within the function where it is declared but destroyed only after the program execution has finished. An ideal time to use a static variable would be to save values in a recursive function.

void static_addition()
{
  static int i = 10;
  i++;
  cout << i;
}
int main()
{
  static_addition(); // Output = 11
  static_addition(); // Output = 12
  static_addition(); // Output = 13
}

 

Extern variables

Extern variables declared allows us to access a variable in a file which is declared as a global variable in one file and then can be used in a separate file.

What is C++ Namespace?

 

C++ Namespace is a declarative area that gives the names of the types, functions, variables, etc. inside of it as a scope. When you were first starting to learn the C++ language, you might have noticed a common line which was “using namespace std” in all your basic applications. This is because the entire library is defined in its own namespace called std. Declaring std, gives you direct access to the names of the functions and classes within the C++ library, without having to insert each one with std::.

As you eventually reach an advanced level of understanding of C++, you may not want to declare the standard C++ library by inserting “using namespace std” if your code will only be using a small amount of the library otherwise it would cause name conflicts during compiling. But if your code has several references to library names, then it’s beneficial to declare the std library.

Purpose of c++ Namespaces 

In simple terms, C++ Namespace is used to organize code by localizing the name of variables in order to avoid name collisions which is useful for large projects. An example would be if you had a program where you defined a class Overflow and a library used in your program contains a class called Overflow as well. This would lead to problems in compiling as there is a conflict with the names because both names are stored in the global namespace. The compiler has no way of knowing which version of the Overflow class is referring to within your code. If we were to create a separate namespace for each Overflow class, the program would have no conflicts with the name of the class.

Creating your own c++ Namespaces example

 

#include <iostream>
using namespace std;
 
// first name space declaration
namespace first_space
{
void display_line()
{
cout << "Inside first namespace" << endl;
}
}
 
// second name space declaration
namespace second_space
{
void display_line()
{
cout << "Inside second namespace" << endl;
}
}
 
int main() {
 
// Calls function from first name space.
first_space::display_line();
 
// Calls function from second name space.
second_space::display_line();
 
return 0;
}

 

Control Led with Arduino, Bluetooth, and Android

This article shows the steps on how to control led with arduino, Bluetooth and Android. Normally the content I post is about C++ concepts, but since this code was used in my latest university engineering project, I wanted to break down and show 3 different technologies being combined together for an application. You can find more details of that project on my personal website.

Click here to download the source code

Setting up the hardware and IDE

You will need the following to control led with arduino

The schematic of the Bluetooth module to the Arduino UNO Board

arduino-bluetooth

Setup the Bluetooth code and Library

The tutorials which are currently online regarding the Bluetooth communication code are outdated and I was trying to use that old code for my project, which ended up being a very painful experience, as I spent 3 weeks trying to get the Bluetooth code to work. Luckily I eventually found a solution. That is to use a Bluetooth library dedicated to work with the Arduino microcontroller. The library is called the Bluetooth SPP Library.

bluetoothspp

Once the Bluetooth library has been set up and imported in Android Studio, use the code below for the Bluetooth communication between the Arduino microcontroller and Android app.

MainActivity.java 


Setup the GUI Menu and Buttons

In Android Studio, create the basic GUI by adding in a couple of buttons and use the code below to link up the buttons to the Bluetooth code.

led-switch-menu

IrrigationControl.java 

Arduino code
Once the Android app code is complied and running, we can then implement the Aruduino code that will receive the bluetooth commands from the Android app and control the LED. Copy and paste the codebelow into the Arduino IDE and compile the code. Once it’s been compiled, send it to the Arduino microncontroller via USB.

ATM Code in C++ – 8th C++ Practice Assignment

In this C++ practice assignment, the task is to implement an ATM Code in C++ that will do the following:

  1. Enter the account balance
  2. Enter in the money to deposit
  3. Calculate the final balance
  4. Calculate the interest
  5. Display the number of $50 notes available
  6. Generate a random value for the variable amount2Deposit
  7. Display all values to the screen

Const:  As you can see in the ATM code in c++, we have three const declarations for the variables BANKNOTE, INTEREST, MIN_DEPOSIT, and MAX_DEPOSIT. The reason we are using the const keyword in the declaration is to prevent modifications to the data. In simple words, it’s going to be the same assigned value when the program is running.

//----------------------------------------------------------
// Sample test B
// ATM Program
//----------------------------------------------------------
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <iomanip>
 
using namespace std;
 
//--------------------------------------------------
// Global variables
//--------------------------------------------------
const int BANKNOTE = 50;
const double INTEREST = 0.065;
int const MIN_DEPOSIT = 100, MAX_DEPOSIT = 10000;
double accountBalance;
 
int Amount1Deposit, Amount2Deposit;
double totalBalance1, totalBalance2, totalInterest1, totalInterest2;
int noOf50s;
 
//--------------------------------------------------
// Function prototypes
//--------------------------------------------------
int getBanknotes(double & amount);
int getRandom();
int main()
{
cout << "Enter in the account balance\n"; cin >> accountBalance;
 
// For Amount1, the user will enter in the value
// To Deposit
cout << "\nEnter in Amount1 to deposit\n"; cin >> Amount1Deposit;
 
// Calculate final balance
totalBalance1 = accountBalance + Amount1Deposit;
 
// Calculate interest
totalInterest1 = totalBalance1 * INTEREST;
// Display the original balance, amount to withdraw
// number of banknotes, final balance and interest after one year
// For Account 1
cout << "\nAccount 1 Information\n";
cout << "Original Balance" << setw(20) << accountBalance << "\n";
cout << "Amount to Deposit" << setw(18) << Amount1Deposit << "\n";
cout << "Number of $50 Notes" << setw(18) << getBanknotes(totalBalance1) << "\n";
cout << "Final Balance" << setw(30) << totalBalance1 << "\n";
cout << "Interest after 1 Year" << setw(20) << totalInterest1 << "\n";
 
// Generate a random value for amount2Deposit and display
// number of banknotes, final balance and interest after one year
// For Account 2
// Please note here that the columns have not been properly formatted but the objective of the whole program works
Amount2Deposit = getRandom();
totalBalance2 = accountBalance + Amount2Deposit;
 
totalInterest2 = totalBalance2 * INTEREST;
 
cout << "\nAccount 2 Information\n";
cout << "Original Balance" << accountBalance << "\n";
cout << "Amount to Deposit" << Amount2Deposit << "\n";
cout << "Number of $50 Notes " << getBanknotes(totalBalance2) << "\n";
cout << "Final Balance " << totalBalance2 << "\n";
cout << "Interest after 1 Year" << totalInterest2 << "\n";
 
return 0;
}
 
//--------------------------------------------------------------
// Get Bank Notes function implementation
// This will calculate how many 50 dollar notes are required
//--------------------------------------------------------------
int getBanknotes(double& amount)
{
return noOf50s = amount / BANKNOTE;
}
 
//--------------------------------------------------------------
// Get Random function implementation
//--------------------------------------------------------------
int getRandom()
{
// Seed the time
srand(time(NULL));
 
// Generates and returns an integer
// random number in the range 100 and 10000.
return Amount2Deposit = rand()%(MAX_DEPOSIT - MIN_DEPOSIT + 1) + MIN_DEPOSIT;
}

 

Heap sort algorithm in C++

The heap sort algorithm is based on the binary heap data structure which is similar to the selection sort, as firstly we find the maximum element and place the maximum element at the end and repeat the same process.

The steps of how the algorithm works

  1. Create a heap data structure which can be Max-heap or min-heap
  2. Once the heap is built, we put the first element of the heap in the array, which can either be the largest or smallest
  3. Use the remaining elements to repeatedly pick the first element of the heap and put it into the array
  4. Repeat the same process until we have the complete sorted list in the array

Visualization of the algorithm

We can build a heap by working through the unordered array in a linear fashion

heapsort part 1

After the heap has been built, we can now sort the values

heapsort part 2

Code implementation in C++


#include &amp;amp;amp;lt;iostream&amp;amp;amp;gt;

using namespace std;

void heapsort(int[], int);
void buildheap(int [], int);
void satisfyheap(int [], int, int);

int main()
{
int a[10];
int i, size;

cout &amp;amp;amp;lt;&amp;amp;amp;lt; "Enter in the size of the list\n";
cin &amp;amp;amp;gt;&amp;amp;amp;gt; size;

cout &amp;amp;amp;lt;&amp;amp;amp;lt; " Enter " &amp;amp;amp;lt;&amp;amp;amp;lt; size &amp;amp;amp;lt;&amp;amp;amp;lt; " elements ";

// Go through the values
for(int i = 0; i &amp;amp;amp;lt; size; i++)
{
cin &amp;amp;amp;gt;&amp;amp;amp;gt; a[i];
}

heapsort(a, size);

}

void heapsort(int a[], int length)
{
buildheap(a, length);
int heapsize, i, temp;
heapsize = length - 1;
for( i=heapsize; i &amp;amp;amp;gt;= 0; i--)
{
temp = a[0];
a[0] = a[heapsize];
a[heapsize] = temp;
heapsize--;
satisfyheap(a, 0, heapsize);
}
for( i=0; i &amp;amp;amp;lt; length; i++)
{
cout &amp;amp;amp;lt;&amp;amp;amp;lt; "\t" &amp;amp;amp;lt;&amp;amp;amp;lt; a[i];
}
}

void buildheap(int a[], int length)
{
int i, heapsize;
heapsize = length - 1;
for( i=(length/2); i &amp;amp;amp;gt;= 0; i--)
{
satisfyheap(a, i, heapsize);
}
}

void satisfyheap(int a[], int i, int heapsize)
{
int l, r, largest, temp;
l = 2*i;
r = 2*i + 1;

if(l &amp;amp;amp;lt;= heapsize &amp;amp;amp;amp;&amp;amp;amp;amp; a[l] &amp;amp;amp;gt; a[i])
{
largest = l;
}
else
{
largest = i;
}
if( r &amp;amp;amp;lt;= heapsize &amp;amp;amp;amp;&amp;amp;amp;amp; a[r] &amp;amp;amp;gt; a[largest])
{
largest = r;
}
if(largest != i)
{
temp = a[i];
a[i] = a[largest];
a[largest] = temp;
satisfyheap(a, largest, heapsize);
}
}

Roulette in C++ – 7th C++ Practice Assignment

roulette

Roulette in c++ is a popular casino game that we will be implementing in this practice assignment. If you don’t know what Roulette is, it’s a casino game, where the player chooses to place bets on either a single number or a range of numbers, the colors red or black, or whether the number is odd or even.

This implemented version of roulette in c++ is only basic, the program flow follows as this

  1. The Game starts
  2. The user places how much he/she wants to bet
  3. The user chooses either to bet on a specific number, black or red, or an odd/even number
  4. The game will generate the random number
  5. The game will decide whether the player wins or loses
//----------------------------------------------------
// Roulette in C++
//----------------------------------------------------
#include <iostream>
#include <string>
#include <iomanip>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{

    // Set as CONSTANT for Random number generation
    int const MIN_NUMBER = 1, MAX_NUMBER = 36;
    int number;
    int random;
    int my_money;
    int starting_money;

    double bet, winnings = 0;

    // Use arrays for player decision
    char gametype;
    char evenodd;
    char blackred;
    char stop = 'N';

    // Main Menu Screen
    cout << "Welcome to ROULETTE\n\n";
    cout << "With how much money do you want to start?\n";
    cin >> starting_money;
    my_money = starting_money;

    while (my_money > 0 && stop != 'Y')
    {
        my_money = my_money + winnings;
        winnings = 0;
        cout << "How much would you like to bet?\n";
        cin >> bet;

        while (bet > my_money)
        {
            cout << "How much would you like to bet?\n";
            cin >> bet;
        }


        cout << "Would you like to bet on a specific number (N), on odd/even (O) or on Black/Red(B)? ";
        cin >> gametype;

        // User selects a specific number to place bet on
        if (gametype == 'n' || gametype == 'N')
        {
            cout << "What number would you like to bet on? "; cin >> number;
            if (number == 00)
                number = 37;

            srand(time(NULL));
            random = rand() % (MAX_NUMBER - MIN_NUMBER + 1) + MIN_NUMBER;

            //cout << "The ball landed on " << random << "\n";

            // Lose
            if (number != random)
            {
                cout << "The ball landed on " << random << "\n";
                cout << "You lose $" << bet << "\n";
                winnings -= bet;
            }
            // Win
            else
            {
                cout << "The ball landed on " << random << "\n";
                cout << "You win $" << 35 * bet << endl;
                winnings += 35 * bet;
            }
        }

        // User selects even or odd
        if (gametype == 'o' || gametype == 'O')
        {
            cout << "Would you like to bet on even (E) or odd (O)? "; cin >> evenodd;

            srand(time(NULL));
            random = rand() % (MAX_NUMBER - MIN_NUMBER + 1) + MIN_NUMBER;
            cout << "The ball landed on " << random << endl;

            // selects EVEN
            if (evenodd == 'E')
            {
                // even win
                if (2 * (random / 2) == random)
                {
                    cout << "You win $" << bet << endl;
                    winnings += bet;
                }
                // even lose
                else
                {
                    cout << "You lose $" << bet << endl;
                    winnings -= bet;
                }
            }

            // selects ODD
            if (evenodd == 'O')
            {
                // odd lose
                if (2 * (random / 2) == random)
                {
                    cout << "You lose $" << bet << endl;
                    winnings -= bet;
                }
                // odd win
                else
                {
                    cout << "You win $" << bet << endl;
                    winnings += bet;
                }
            }
        }

        if (gametype == 'B' || gametype == 'b')
        {
            cout << "would you like to bet on black (B) or red (R)? "; cin >> blackred;

            srand(time(NULL));
            random = rand() % (MAX_NUMBER - MIN_NUMBER + 1) + MIN_NUMBER;
            cout << "The ball landed on " << random << endl;

            if (blackred == 'B' || blackred == 'b')
            {
                if (random == 2 || random == 4 || random == 6 || random == 8 || random == 10 || random == 11 || random == 13 || random == 15 || random == 17 || random == 20 || random == 22 || random == 24 || random == 26 || random == 28 || random == 29 || random == 31 || random == 33 || random == 35)
                {
                    cout << "You win $" << bet << endl;
                    winnings += bet;
                }
                else
                {
                    cout << "You lose $" << bet << endl;
                    winnings -= bet;
                }
            }

            if (blackred == 'R' || blackred == 'r')
            {
                if (random == 2 || random == 4 || random == 6 || random == 8 || random == 10 || random == 11 || random == 13 || random == 15 || random == 17 || random == 20 || random == 22 || random == 24 || random == 26 || random == 28 || random == 29 || random == 31 || random == 33 || random == 35)
                {
                    cout << "You lose $" << bet << endl;
                    winnings -= bet;
                }
                else
                {
                    cout << "You win $" << bet << endl;
                    winnings += bet;
                }
            }
        }
        cout << "Do you want to stop, yes(Y) or no(N)?";
        cin >> stop;
    }

    // Final Results
    my_money = my_money + winnings;
    cout << "You won a total of $" << my_money - starting_money << "\nAnd you currently have a total of $" << my_money;
}