You are on page 1of 28

C++ Program Structure

Bookmark this page


A C++ program has a very specific structure in terms of how the code is written
and some key elements that you use in your C++ programs. The simplest of
C++ programs is shown here.

1. #include <iostream>
2.
3. int main()
4. {
5. std::cout << "Hello World!";
6. return 0;
7. }

In this simple program we notice some elements listed. The line numbers are
used for reference only and are not part of the program code.

Line 1: this is known as a pre-processor directive. it instructs the compiler to


locate the file that contains code for a library known as iostream. This library
contains code that allows for input and output to streams, such as the console
window.
Line 3: Every C++ program must have a method known as main(). It is referred
to as the entry point for the application when you start execution of the program
on your computer. The int portion is the return type of the method. The empty
parentheses () after the method name indicate that this a method and that it
takes no arguments, in other words, there are no parameters for passing in
values.
Line 4: Method bodies in C++ start with an open curly brace. Line 5: This code
uses a method known as cout (pronounced "see out") to send the text Hello
World! to the console for output and display. The std:: prefix to this command is
a way of indicating that cout is part of a namespace known as std. The :: is is
used to indicate that cout is part of the std namespace.

Also notice that the line ends with a semi-colon. C++ statements are terminated with
semi-colons.

Line 6: The return statement is used to end a function or method when a value
is expected to be sent back to a caller. In this case, the caller is the operating
system and the value returned is an integer value of 0. If the program reaches
this statement, returning a value of 0 is an indication to the operating system
that the code executed successfully. In the past, programmers would return 0 to
indicate successful execution and non-zero values to indicate that an error had
occurred in the program somewhere.
Line 7: This line closes out the body of the function main() and is necessary so
the compiler knows where the function or method ends, but is also used for
other purposes that will be covered later in the course on variable scope and
visibility.
Type Name Bytes Alias Range

int 4 signed –2,147,483,648 to 2,147,483,647

unsigned int 4 unsigned 0 to 4,294,967,295

__int8 1 char -128 to 127

unsigned __int8 1 unsigned char 0 to 255

__int16 2 short, short int, signed short int –32,768 to 32,767

unsigned __int16 2 unsigned short, unsigned short 0 to 65,535


int

__int32 4 signed, signed int, int –2,147,483,648 to 2,147,483,647

unsigned __int32 4 unsigned, unsigned int 0 to 4,294,967,295

__int64 8 long long, signed long long –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

unsigned __int64 8 unsigned long long 0 to 18,446,744,073,709,551,615

short 2 short int, signed short int -32,768 to 32,767

unsigned short 2 unsigned short int 0 to 65,535

long 4 long int, signed long int –2,147,483,648 to 2,147,483,647

unsigned long 4 unsigned long int 0 to 4,294,967,295

long long 8 none –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

unsigned long long 8 none 0 to 18,446,744,073,709,551,615

float 4 none 3.4E +/- 38 (7 digits)

double 8 none 1.7E +/- 308 (15 digits)

long double 8 none 1.7E +/- 308 (15 digits)

Type Name Bytes Alias Range

char 1 none –128 to 127 by default 0 to 255 when compiled by using /J

signed char 1 none -128 to 127

unsigned char 1 none 0 to 255

wchar_t, char16_t, and 2 or 4 __wchar_t 0 to 65,535 (wchar_t & char16_t), 0 to 4,294,967,295 (char32_t)
char32_t

Type Name Bytes Alias Range

bool 1 none true or false

enum varies none dependant on the enclosed data types


Choosing the correct data type is important in your applications to ensure that
you can represent your data efficiently and correctly. Some examples of this
would be;

 making use of short rather than int if your data range permits
 using a double rather than a float to get greater a accuracy for values
representing money
 using a wchar_t for character data that doesn't fit in the standard ASCII
character set, such as Japanese kanji

Introducing Variables
Bookmark this page
Variables are identifiers that you create to hold values or references to objects
in your code. A variable is essentially a named memory location.

When you create a variable in C++, you must give it a data type. You can
assign a value to the variable at the time you create it or later in your program
code. This is known as initializing the variable. Even though you can initialize a
variable separate from its creation, you must assign the data type when you
define the variable. C++ will not allow you to use an uninitialized variable to help
prevent unwanted data from being used in your application. The following code
sample demonstrates declaring a variable and assigning a value to it. C++
supports two methods of initializing a variable.

int myVar = 0;
int yourVar{1};

C++ has some restrictions around identifiers that you need to be aware of.

First off, identifiers are case-sensitive because C++ is a case-sensitive


language. That means that identifiers such as myVar, _myVar, and myvar, are
considered different identifiers.

Identifiers can only contain letters (in any case), digits, and the underscore
character. You can only start an identifier with a letter or an underscore
character. You cannot start the identifier with a digit. myVar and _myVar are
legal but 2Vars is not.

C++ has a set of reserved keywords that the language uses. You cannot use
these keywords as an identifier in your code. You may choose to take
advantage of the case-sensitivity of C++ and use Long as an identifier to
distinguish it from the reserved keyword long, but that is not a recommended
approach.

To keep up to date on the reserved keywords for C++ you should always refer
to the C++ standard but the current standard lists reserved keywords in the C++
Standard document found here.
Introducing Constants

Similar to a variable, a constant expression is a named memory location for a


value used in your application. The difference is that, as you might expect, a
constant expression cannot have its value change in the program during run
time. C++ uses the keyword const to indicate that an expression is a constant.

When you declare a constant in C++, you must assign a literal value to that
constant at the same time. You cannot assign it later in program nor can you
change the value in code later. Also, because the value cannot be changed,
you cannot initialize a constant with a variable or any other value that will have
its value modified during runtime.

Type Conversions
Casting refers to converting one data type to another. Some data conversions
are not possible while some are possible but result in data loss. C++ can
perform many conversions automatically, what is known as implicit casting or
implicit conversion. For example, attempting to convert a smaller data type to
larger data type as shown here:

int myInt = 12;


long myLong;
myLong = myInt;

In the first line, we declare an integer data type and assign it a value of 12. The
next line declares a long data type and in the third line, we assign the integer
data type value to the long data type. C++ automatically converts the data type
for you. This is known as a widening conversion. Some programmers also call
this an expanding assignment. We are expanding or widening the data type to a
larger one. In this case, there is no loss in data. The following table highlights
some potential data conversion problems.

This table only deals with numeric data type conversions. There are other
conversion types such as from character to numeric or numeric to character, or
among character types. C++ also uses the boolean type that represents true or
false. If you assign a zero value to a bool variable, it will be converted to false.
Any non-zero value is converted to true.
When you want to explicitly perform a conversion or cast, you can use the type
cast features of C++. For example, the previous widening conversion in the int
to long cast was implicit but you can also tell the compiler that you are know
what you are doing by using the type cast statement as in:

long myLong = (long)myInt;

// or you can use this version as well

long myLong = long(myInt);

C++ also provides a cast operator that is more restrictive in its usage. This in
the form static_cast (type). This static cast operator can be used for
converting numeric values or to numeric values. As an example:

char ch;

int i = 65;

float f = 2.5;

double dbl;

ch = static_cast<char>(i); // int to char

dbl = static_cast<double>(f); // float to double

Complex Data Types (Arrays)

So far you have been introduced to the intrinsic data types that C++ supports.
These are types that contain the data literals directly. The int type directly stores
the literal integer value, for example.

C++ also provides support for complex data types. These are also referred to as
compound data types. Mostly because they store more than one piece of data
or potentially more than one data type.

An array is a set of objects that are grouped together and managed as a unit.
You can think of an array as a sequence of elements, all of which are the same
type. You can build simple arrays that have one dimension (a list), two
dimensions (a table), three dimensions (a cube), and so on. Arrays in C++ have
the following features:

 Every element in the array contains a value.


 Arrays are zero-indexed, that is, the first item in the array is element 0.
 The size of an array is the total number of elements that it can contain.
 Arrays can be single-dimensional, multidimensional, or jagged.
 The rank of an array is the number of dimensions in the array.
Arrays of a particular type can only hold elements of that type. This means that
you cannot store integers, longs, and character data types in the same array.
Creating and Using Arrays

When you declare an array, you specify the type of data that it contains and a
name for the array. To declare a single-dimensional array, you specify the type
of elements in the array and use brackets, [] to indicate that a variable is an
array. The following code example shows how to create a single-dimensional
array of integers with elements zero through nine.

int arrayName[10];

You can also choose to create an array and initialize it with values at the same
time as in the following example that declares and integer array and assigns
values to it. The compiler knows how large to make the array by the number of
values in the curly braces:

int arrayName[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

You can also declare an array and only initialize some of the elements:

int arrayName[10] = {1, 2, 3};

In this case, we have declared an array of size 10 but have only assigned
values to the first three elements. The compiler will initialize the remaining
elements to the default value for the data type the array holds. In this case, int
data type, the remaining values are initialized to 0.

Accessing Data in an Array

You can access data in an array in several ways, such as by specifying the
index of a specific element that you require or by iterating through the entire
array and returning each element in sequence.

The following code example uses an index to access the element at index two.

//Accessing Data by Index


int oldNumbers[] = { 1, 2, 3, 4, 5 };

//number will contain the value 3


int number = oldNumbers[2];

Note: Arrays are zero-indexed, so the first element in any dimension in an array
is at index zero. The last element in a dimension is at index N-1, where N is the
size of the dimension. If you are using some other languages, such as C#, and
you attempt to access an element outside this range, the C# runtime will throw
an exception (error). C++ doesn't offer such protection. If you attempt to access
an element that is outside the bounds of your array, you will still return data, but
you have no idea what that data is.

The reason for this is because an array is simply a pointer to a memory


location. The first element of the array is the starting memory address for the
entire array. If you have an array of integer data types, then the number of the
elements multiplied by the size of the int data type on your system, determines
how much memory is used by the array, and at the same time, permits the
access of the elements in the array by performing math on the memory address
to get at the required element. If you attempt to access oldNumbers[5], the
program will simply return the data found at the memory address that is the next
memory address location beyond the last array element. This can be a
dangerous situation and is in fact, the result of some security issues found in
software.

You can also iterate through an array by using a for loop. You will cover loops in
module 3 so don't worry if you don't completely understand this example at this
time. Essentially, the for loop starts at 0 and repeats the portion in the curly
braces {} for each of the five steps in the loop.

The following code example shows how to use a for loop to iterate through an
array.

//Iterating Over an Array


int oldNumbers[] = { 1, 2, 3, 4, 5 };
for (int i = 0; i < 5; i++)
{
int number = oldNumbers[i];
...
}

Strings

Strings are a series of characters. C++ represents strings in one of two ways.
The first maintains backward compatibility with the C language and represents
the string as a character array. There is one aspect to a C-style string that is
important to note. The last character of every string you store is the null
character string, typically represented by the ASCII code for 0 which is \0. This
is necessary so that the compiler knows when the string ends. An example
demonstrates a C-style string stored in a character array:

char isAString[6] = { 'H', 'e', 'l', 'l', 'o', '\0'};


char isNotAString[5] = { 'H', 'e', 'l', 'l', 'o'};
cout << isAString << endl;
cout << isNotAString << endl;

The most common mistake made by users of the C-style string is to forget to
make the char array large enough to accommodate the \0 character, but also
forgetting include the \0. In the previous example, a programmer might think
that an array of size 5 would be large enough to contain Hello because that's
how many characters are in the word. However, the null character would not be
included in the second array, which could result in errors in code that uses this
array. The reason is that C++ does not consider the isNotAString array to be a
string.
Consider the output displayed in Figure 2.1. Note that the first output correctly
terminates because C++ encountered the null (\0) character. The second did
not terminate and output the contents of adjacent memory.

An alternative method of declaring a character array for use as a string is to


simply initialize it with a string literal. A string literal is a sequence of characters
enclosed in the double quotes ("). For example:

char isAString[6] = "Hello";


char isAnotherString[] = "Array size is inferred";

In the previous example, the first line creates an array of size 6 and assigns the
string literal Hello to the array. The second example lets the compiler infer the
size from the string literal itself. Note that neither of these two string literals
specifies a \0 character. The compiler will implicitly add that for you. However,
caution is advised in the first line to ensure that you allow enough room in the
array size specified for the null character. If you create an array that is larger
than required for the string literal along with the null character, then C++ simply
fills the remaining elements of the array with null characters.

The string Class If the use of character arrays, single quoted characters, and
null termination characters are making you think that strings aren't worth the
hassle, consider the string class instead. The ISO/ANSI standard helped to
expand the string handling capabilities of C++ by adding the string class.

In order to use the string class, you have to include the string header file. We
have not covered namespaces yet but to make typing much easier, you would
add a using statement as in the following example.

using namespace std;


string myString = "Hello!";
std::string myNewString = "Less typing";

Without the using directive, you would have to type std::string every time
you wanted to use the string class in your code, as in the second line above.

As you can see from the code example, you use string in the same manner in
which you would use any other data type in C++. You also do not need to add a
null character to terminate your string.

Structures
Arrays can store multiple pieces of data in one compound data type but recall,
the data types must all be of the same type. If that is the case, how might you
store multiple pieces of data in one type, where the individual pieces are of
different data types? For example, let's say that we want to store information
about a coffee bean. We might want to store information about the bean type,
its strength, and perhaps which country it originated from. In this case, we could
use all strings to store that information but what if the strength was intended to
be a number from 1 to 10. In this case, we would want to store two strings and
one integer in our coffee bean data type.

We haven't covered classes yet, which is another data type we could use, but
instead, we will use a structure (struct) to store this information. Structures are
known as user-defined types. You define the struct by giving it a name and then
adding the member data types as in the following example:

struct coffeeBean
{
string name;
string country;
int strength;
};

Recall that in order to use the string data type in our struct, the C++ file that
contains the struct must include the string header file. This code snippet also
assumes that using namespace std; has also been included.
Once we have defined the structure, we can then use it in our code the same as
any other data type. To use the coffeeBean struct in your code, you simply
declare a new variable of that type as shown in this example.

struct coffeeBean
{
string name;
string country;
int strength;
};

coffeeBean myBean = { "Strata", "Columbia", 10 };


coffeeBean newBean;
newBean.name = "Flora";
newBean.country = "Mexico";
newBean.strength = 9;
cout << "Coffee bean " + newBean.name + " is from " +
newBean.country << endl;

You can assign values to a struct using one of the methods seen here. For
myBean, we assign values in the curly braces while for newBean, we use the
dot notation. You can also access the values of the the struct members using
the dot notation as well, shown in the cout statement at the end.

Unions

A union, in C++, is similar to a structure in that it can store multiple, disparate


data types. The differentiation is that a union can only store one piece of data at
a time. What does that signify? It's best represented using an example.

union numericUnion
{
int intValue;
long longValue;
double doubleValue;
};
numericUnion myUnion;
myUnion.intValue = 3;
cout << myUnion.intValue << endl;
myUnion.doubleValue = 4.5;
cout << myUnion.doubleValue << endl;
cout << myUnion.intValue; cout << endl;

In this example, we define a union called numericUnion and then create a


variable of that type, called myUnion. We first assign the value 3 to
the intValue field and then output it. Next we assign the value 4.5 to
the doubleValue field and output that. The example shows how the union
works when on the second to last line, we try to output the value
for intValue again. In the output, it results in 0 rather than 3. The reason is
that once we assign a value to doubleValue, what was contained
in intValue is lost. The union can only store a value in one of its fields at a
time.

Why use a union over a struct if it can only hold one piece of data at a time?
Consider a situation where you are programming an application that will run on
a device with limited memory. You would like to use a data type that can
support multiple types internally like a struct, but not necessarily all at the same
time. For example, part numbers for components in manufacturing where the
part number may be a number or perhaps a string, depending on the
manufacturer of the part. In this case, you could use the union to represent a
numeric and a string data type internally but only assign the proper data type
based on the part number.

Enumerations

In the topics on variables and constants, it was noted that anytime you want to
create a value for use in a program, where the value should never change, you
used a constant. An enumeration can be considered a way to create what are
known as symbolic constants. The most common example is to use an enum to
define the day of the week. There are only seven possible values for days of the
week, and you can be reasonably certain that these values will never change.

To create an enum, you declare it in your code file with the following syntax,
which demonstrates creating an enum called Day, that contains the days of the
week:

enum Day { Sunday, Monday, Tuesday, Wednesday, Thursday,


Friday, Saturday };

By default enum values start at 0 and each successive member is increased by


a value of 1. As a result, the previous enum 'Day' would contain the values:

 Sunday = 0

 Monday = 1

 Tuesday = 2

 etc.

You can change the default by specifying a starting value for your enum as in
the following example.

enum Day { Sunday = 1, Monday, Tuesday, Wednesday,


Thursday, Friday, Saturday };

In this example, Sunday is given the value 1 instead of the default 0. Now
Monday is 2, Tuesday is 3, etc.
The keyword enum is used to specify the "type" that the variable Day will be. In
this case, an enumeration type. Consider the following code sample:

enum Day { Sunday = 1, Monday, Tuesday, Wednesday,


Thursday, Friday, Saturday };
Day payDay;
payDay = Thursday;
cout << payDay << endl;

The first line defines the enumeration Day and assigns seven values to the
enum. Sunday is listed as the first day of the week and is initialized with the
value one.

The second line declares a new variable called payDay which is of


the Day enum type. In the third line, payDay is assigned a value from the list of
values, in this case Thursday. Finally, the last line outputs the value
of payDay to the console window. If you run this code, you will notice that the
last line outputs 5 and not Thursday. Internally, the constants in the enum are
used as numbers and not as the textual representation you assign to them.

C++ Operators

Because you will start to learn about control statements in C++, it's important to
understand the C++ operators that exist in the language first, as they play an
important role in control statements.

You will work with comparison operators to determine if values are equal,
greater, or less than each other. C++ also allows you to use mathematical
operators for incrementing values to help control the number of iterations in a
loop. You can also make use of bitwise operators to speed up some operations
in your code.
if Statements

if Statements

In C++, if statements are concerned with Boolean logic. If the statement


is true, the block of code associated with the if statement is executed. If the
statement is false, control either falls through to the line after the if statement,
or after the closing curly brace of an if statement block.
The following code sample demonstrates an if statement to determine if a
response contains a value of y or Y.

char response = 'y';


if (response == 'y' || response == 'Y')
{
cout << "Positive response received" << endl;
}

Note the use of curly braces in the code sample. You can eliminate the curly
braces if your statement to execute is a single line statement. C++ understands
that if no curly braces are used, the line immediately after
the if(condition) will be executed if the condition is true. Otherwise that
line of code is not executed and the code resumes after that line. If you need to
have multiple statements execute if the condition is true, then you must use
curly braces to surround the body of the if structure as in the code sample.

TIP: To avoid confusion as to which lines will execute for a true condition, a
recommended practice is to always use curly braces for your if statement.

In C++, if statements can also have associated else clauses.


The else clause executes when the if statement is false.

The following code example shows how to use an if else statement to


execute code when a condition is false.

if else Statements

string response;
if (response == "connection_failed")
{
// Block of code executes if the value of the response
variable is "connection_failed".
}
else
{
// Block of code executes if the value of the response
variable is not "connection_failed".
}

if statements can also have associated else if clauses. The clauses are
tested in the order that they appear in the code after the ifstatement. If any of
the clauses returns true, the block of code associated with that statement is
executed and control leaves the block of code associated with the
entire if construct.

The following code example shows how to use an if statement with an else
if clause.
else if Statements

string response;
if (response == "connection_failed")
{
// Block of code executes if the value of the response
variable is "connection_failed".
}
else if (response == "connection_error")
{
// Block of code executes if the value of the response
variable is "connection_error".
}
else
{
// Block of code executes if the value of the response
variable is neither above responses.
}

You can create as many else if blocks as necessary for your logic, or until
you become completely lost from too many else if clauses. If you require
any more than five else if clauses, you might want to consider
the switch statement, presented next.

switch Statements

If there are too many else if statements, code can become messy and
difficult to follow. In this scenario, a better solution is to use a switchstatement.
The switch statement simply replaces multiple else if statements. The
following sample shows how you can use a switchstatement to replace a
collection of else if clauses.

switch Statement

char response = 'y';


switch (response)
{
case 'y':
// Block of code executes if the value of response is
y.
break;
case 'Y':
// Block of code executes if the value of response is
Y.
break;
case 'n':
// Block of code executes if the value of response is
n.
break;
default:
// Block executes if none of the above conditions are
met.
break;
}

Notice that there is a block labeled default:. This block of code will execute
when none of the other blocks match. The default block is optional.

In each case statement, notice the break keyword. This causes control to
jump to the end of the switch after processing the block of code. If you omit
the break keyword, the application may not perform as you anticipate. In other
languages, such as C#, omitting the break; keyword will cause the code to no
longer compile.

Without the break statement, the code will "fall through" to the remaining cases
until it encounters a break statement. Be very careful in using fall through logic
in your switch statements. The most common use for a fall through scenario is
when you want to handle multiple cases with a single statement or set of
statements.

If you are coming from another programming language, such as C#,


that also uses the switch statement, you might notice that in the C#
language, you can use string values in your switch statements and
don't have to use integers or enumerated types. C++ switch
statements support the following data types as expressions:

 intrinsic data types such as int or char

 enumerations

The Conditional (Ternary) Operator

The C++ conditional operator is also known as a ternary operator because it


takes three operands. How this operator functions is somewhat similar to an if
statement or a switch statement, but in a more compact form and for one single
Boolean value with one of two possible outputs. That is to say, the first
operand is evaluated as a Boolean result. If the result is true, then the second
operand will be the one evaluated. Otherwise, the third operand will be
evaluated. A sample helps amplify this.
#include <iostream>
using namespace std;
int main()
{
int i = 1, j = 2;
cout << ( i > j ? i : j ) << " is greater." << endl;
}

In this example, we have two integer variables, i and j which are initialized to 1
and 2 respectively. The ternary operator is embedded inside the cout statement
and essentially follows this pattern:

1. it checks whether i is greater than j

2. it outputs the proper numeric value along with is greater.

In the code example here, j is greater than i so the condition evaluates to false
and the value for j (2), is output to the console along with the text is greater. In
other words, the output is "2 is greater." If i was 5 and j was 2, the output would
be, "5 is greater."

i > j ? i : j where i is greater than j then the bold value


is selected

i > j ? i : j where j is greater than i, then the bold


value is selected
for Loops

The for loop executes a block of code repeatedly until the specified expression
evaluates to false. You can define a for loop as follows.

for ([initializer(s)]; [condition]; [iterator])


{
// code to repeat goes here
}

The [initializer(s)] portion is used to initialize a value, or values, as a


counter for the loop. On each iteration, the loop checks that the value of the
counter is within the range to execute the for loop, specified in
the [condition] portion., and if so, execute the body of the loop. At then
end of each loop iteration, the [iterator] section is responsible for
incrementing the loop counter.

The following code example shows how to use a for loop to execute a code
block 10 times.

for Loop
for (int i = 0 ; i < 10; i++)
{
// Code to execute.
}
In this example, i = 0; is the initializer, i < 10; is the condition, and i++ is
the iterator.

while Loops

A while loop enables you to execute a block of code while a given condition
is true. For example, you can use a while loop to process user input until the
user indicates that they have no more data to enter. The loop can continue to
prompt the user until they decide to end the interaction by entering a sentinel
value. The sentinel value is responsible for ending the loop.

The following code example shows how to use a while loop.

while Loop

string response;
cout << "Enter menu choice " << endl << "More" << endl <<
"Quit" << endl;
cin >> response;

while (response != "Quit")


{
// Code to execute if Quit is not entered

// Prompt user again with menu choices until Quit


is entered
cout << "Enter menu choice " << endl << "More" <<
endl << "Quit" << endl;
cin >> response;
}

It's imperative to include the prompt again, inside the loop braces. Failure
to put this into the loop body will result in an infinite loop because the
sentinel value can never be changed.

do Loops

A do loop, sometimes also referred to as a do...while loop, is very similar to


a while loop, with the exception that a do loop will always execute the body of
the loop at least once. In a while loop, if the condition is false from the start,
the body of the loop will never execute.

You might want to use a do loop if you know that the code will only execute in
response to a user prompt for data. In this scenario, you know that the
application will need to process at least one piece of data, and can therefore
use a do loop.

The following code example shows the use of a do loop.

do Loop

string response;

do
{
cout << "Enter menu choice " << endl << "More" << endl
<< "Quit" << endl;
cin >> response;

// Process the data.

} while (response != "Quit");

A couple of aspects to note about this loop. First of all, the response
variable is declared outside of the loop. This is important due to
scope resolution requirements. If you declare the variable inside the
loop, then the while(response != "Quit") portion will not "see" the
response variable.
Second, note that in comparison with the while loop, the prompt only
needs to be placed inside the loop body and is not required ahead of
the loop. This is possible because the do loop executes the contents
of the loop at least once due to the condition check being at the end
of the loop.

Third, notice the semicolon at the end of the loop. This is required in
the do loop and not in the while or for loop.

Nesting Loops

Nesting of loops is possible in C++. The most common is to nest for loops. An
example of nesting a for loop might be used for games, such as dealing four
hands to card players from a deck of 52. Your outer loop would count from 0 to
51 for the total number of cards in the deck and the inner loop would count from
0 to 3 to represent the 4 hands being dealt. Of course, if you aren't dealing the
entire 52 cards, you can change the outer loop counter to represent that fact.

The following code example shows nesting for loops to output a chess or
checkerboard representation using the characters X and O.

bool alternate = true;

for (int x = 0; x < 8; x++)


{
for (int y = 0; y < 4; y++)
{
if (alternate)
{
cout << "X ";
cout << "O ";

}
else
{
cout << "O ";
cout << "X ";

}
}
alternate = !alternate;

cout << endl;


}
Introduction to Functions
Bookmark this page

Functions are a component of a programming language that permit you to break


down the behavior of an application into discreet pieces of functionality, hence
the name function. A function is essentially a block of C++ code that you give a
name and then call from other locations in your application, when you want the
computer to perform the instructions contained in that function.

You create a function by defining it. The function definition may contain a return
type, a function name, parameters to accept incoming arguments, and finally a
body which contains the code that will execute as part of that
function. Functions may or may not return a value back to the caller and they
may or may not accept arguments passed in to the function.

When you move into more advanced C++ programming, you can also overload
functions. This refers to the practice of using the same function name to refer to
multiple functions that perform different actions. Why would you do
this? Consider a simple scenario where you want to perform addition on some
values so you create a function called Sum(). You could overload Sum() by
creating variants such as:

int Sum(int x, int y)


{
return x + y;
}

int Sum(int x, int y, int z)


{
return x + y + z;
}

The compiler will know which function to call, based on the number of
arguments passed in.
Function Prototypes

When declaring a function, you specify its storage class, return type, name, and
parameters. Some refer to this as the function signature. In C++ it is also
called a function prototype.

In C++, function prototypes belong in header files. Recall that the header file is
what gets imported into other source code files so that the compiler can track
proper use of functions and other aspects of the included files. The function
prototype only contains the function's signature with no implementation
details. The implementation details along with the function signature, define the
function. The function definition exists in the source code file (.cpp).

Function Parameters

A function can accept values that will be used in the statements in the function
body. These values are known as arguments when passed to a function. The
arguments are passed into parameters. Parameters are the placeholders that
are found inside the parentheses of a function declaration, as shown in the
following example where a and b are the parameters. Note that the data types
for these are specified and that the parameters are separated by a comma.

int Sum(int a, int b)


{
return a + b;
}

Your function can specify as many parameters as necessary for the


function to complete its work but for obvious reasons, you don't want
to create a function signature that is so long, your code line wraps. If
your function takes that many parameters, it's worth refactoring it to
reduce the number of parameters.

When calling the function, you use the function name, followed by an
open parenthesis, the arguments that will be passed into the
parameters, and then a closing parenthesis, as shown here:

int result = Sum(2, 3);

Note that you don't have to include the data type specifiers for the
arguments being passed in but you must know the data type the
function expects. This is one of the reasons for declaring a function
prototype prior to using it in code.

Inline Functions

One of the goals for using functions in your code is to create discrete pieces of
functionality in your code that is easier to test and maintain. However, functions
also have an impact on application performance. The reason for this impact
results from the operations that must be performed when a function is
called. For example, registers in the CPU need to be reset, stack pointers are
created, memory is consumed for these pointers and the values that are passed
into and out of the function. For simple functions that may perform only a
single operation or have only a single, simple statement, you might wonder why
creating a function for it is worth the effort.

You can still make use of a function to perform the necessary computation but it
makes more sense to create the function as an inline function. Inline functions
avoid the overhead associated with traditional function calls. You create an
inline function by prefixing it with the inline keyword. A common function found
in applications for a sorting algorithm such as bubble sort, is a swap
function. Swap takes two variables and swaps their values as shown here:

inline void swap(int & a, int & b)


{
int temp = a;
a = b;
b = temp;
}
Using this mechanism, each time that a call to the swap() method is
encountered in your code, the compiler will insert the body of the function in that
location as opposed to making a function call. This example demonstrates what
that would look like.

// Traditional method that results in a function call


swap(5, 6);

// Using an inline function call, the compiler converts the


previous line to this
int temp = a;
a = b;
b = temp;

This avoids the overhead of making a function call because the


contents of the function body are now located at the point where the
functionality is required. Note a couple of points about inline
functions:

 the inline keyword is a compiler directive that is a recommendation


only. The compiler may ignore your request and compile the function
normally resulting in function calls anyway.

 if you are using inline functions and change the function in anyway,
the code needs to be recompiled because the code for that function
will need to be updated in each location it was used.

 use inline functions only for small functions that are used frequently,
not for large functions.

Storage Classes and Scope

MSDN defines storage class as, "A storage class in the context of C++ variable
declarations is a type specifier that governs the lifetime, linkage, and memory
location of objects."

Lifetime refers to how long the variable "hangs around" in memory from the
point at which it is declared and the point at which it is destroyed (the memory it
used is released). For the most part, once a variable goes out of scope, its
memory will be released back to the operating system for reuse.

Linkage refers to the visibility of a variable outside of the file that contains it.

Memory location refers to the place in which the variable is found in


memory. This doesn't refer to the physical memory address as you might
expect but more to the logical division of memory that applies to a running
application. There are two logical memory areas known as the stack and the
heap. The stack is a location in memory where intrinsic data is stored as well
as memory addresses (pointers). It operates in the form of data structure
known as a stack. Like a cafeteria stack of plates, items are pushed on top of
the stack and other items are pushed further down. To remove an item from the
stack, it is popped off, used, and discarded.

The heap, or free store, is a pool of memory that is used to store objects that
dynamically allocated at run time by your application. An object is what you will
learn about in the next topic on object-oriented programming. You create and
destroy objects on the heap by using specific instructions in your program code.

Scope is the term used describe where an identifier is visible in a program. An


identifier is a variable, constant, class, etc. Your identifier is visible from the
point in which you have declared it until the end of its scope. The following
code sample displays different scope for the identifiers used.

1. #include <iostream>
2. int main()
3. {
4. int total = 0;
5. for(int i = 1; i <= 10; i++)
6. {
7. total += i;
8. }
9. std::cout << "The sum of the numbers 1 to 10 is " <<
total << std::endl;
10. std::cout << "Current value of i is " << i <<
std::cout;
11. return 0;
12. }

In the previous code, the variable total is declared inside main() but
outside of the for loop. This means that total is visible (in scope) for
the entire main() method, which also includes inside the for
loop. However, the variable i is declared inside the for loop's
initialization section and is therefore constrained to the scope of the
for loop. The code at line 10 will result in an error in C++ that
indicates the variable is undefined. Anyplace other than inside the
for loop is out of scope for the variable i.

C++ makes use of the following keywords that apply to storage


classes:

 static - identifiers declared with static are allocated when the program
starts and deallocated when the program execution ends. Declaring a
variable as static in a function means that the variable will retain its
value between calls to the function.
 extern - used to declare an object that is defined in another
translation unit of within the enclosing scope but has an external
linkage.

 thread_local - declares that the identifier is only accessible on the


thread in which it is created. This prevents sharing of the identifier
across multiple threads in the same application. This is part of the
C++11 standard.

Introduction

Classes enable you to create your own custom, self-contained, and reusable
types. A class file is often considered a blueprint for objects that you use in your
code. Typically you will create class files to help model real-world objects in
your code.

An example of this might be the software that manages a bank ATM. The
software would need to understand the concept of customers, accounts,
transactions, etc. It's far easier to implement the software application by
modelling these real world objects as software objects (classes) in your code.

In this module, you will gain an introduction to classes in C++ that will cover the
basics only. The second installment of the C++ course will delve deeper into
object oriented concepts in C++.

Creating Classes

Creating Classes and Members

In C++, a class is a programming construct that you can use to define your own
custom types. When you create a class, you are effectively creating a blueprint
for the type. The class defines the behaviors and characteristics, or class
members, which are shared by all instances of the class. You represent these
behaviors and characteristics by defining methods and fields within your class.

Suppose you create a class to represent a rectangle shape in your


program. You use the class keyword to declare a class, as shown in the
following example:

//Declaring a Class
class Rectangle
{
public:
int _width;
int _height;
};
Here we have declared a class called Rectangle and given it two public member
variables called _width and _height, that will be used to represent the width and
height of our rectangle. Note that they are accessible directly because they are
public, as a result of the public: modifier.

Using a Class

Now that we have a class created to represent a rectangle, we can use that in
our code to create instances of a rectangle in our program. When we create a
new rectangle from this class, it is known as a rectangle object and will be given
a unique name. That way ,we can refer to it in our program directly and
distinguish it from other rectangle instances that we might create, should our
program require more than one.

void main()
{
Rectangle outer;
Rectangle inner;

outer._width = 10;
outer._height = 10;

inner._width = 5;
inner._height = 5;
}

In this sample code, we have created two rectangle objects called outer and
inner. Then, using what is known as "dot notation" or the dot operator, we
provide values for the width and height of each rectangle. The outer rectangle
is 10 x 10 and the inner rectangle is 5x5.

Class Initialization

Initialization is an important part of working with your classes in C++. Even


when using intrinsic data types, if you do not initialize the variable for that type
and you access it in your code, you will end up with whatever values are stored
in the memory location that the variable refers to. This is something you want to
avoid doing. You should always initialize your types in C++;

C++ offers a couple of options for initializing your classes. You can initialize the
member variables by using the dot operator and setting the values explicitly or
you can include a constructor in your class that is responsible for initialization
the member variables. You'll see this in the demo video next as well as more
information in the topic on encapsulation.
Introducing Encapsulation

Often considered the first pillar of object-oriented programming,


encapsulation can be used to describe the accessibility of the members
belonging to a class. C++ provides access modifiers and properties to help
implement encapsulation in your classes. While some consider this
accessibility configuration to be the only aspect of encapsulation, others also
define encapsulation as the act of including all data and behavior required of the
class, within the class definition.

We use encapsulation to prevent changing the member variables directly. This


is considered a poor practice because it presents the opportunity for potentially
incorrect values to be assigned to these member variables. This can result in
unexpected behavior or more serious problems with your executing code. It
also helps with debugging of your code.

Introducing Const Objects

Recall that the keyword const was used to indicate that a data type you use in
your code is a constant and cannot have its value changed during application
runtime. Objects in your code can also make use of the const keyword to
indicate that the objects are immutable. Immutable simply means that they
cannot change.

In the next couple of video segments, you will be introduced to const objects
and see a demo of how to use them in code.

You might also like