You are on page 1of 9

Lecture 04: ISO/ANSI C++ Programming Fundamentals

Introduction
C++ is an extension of the language C that was written by Bjarne Stroustrup.in 1979 at Bell
Labs (the called “C with Classes”). It is fast, portable and widely used.
It is an Object Oriented language.

Key Concepts
1. Filename
A source file is the file that contains the C++ code (source code) that is compiled into an
executable file (object code), using a C++ compiler. C++ source files usually have an
extension of .cpp for the VC++ compiler.
Recall: A compiler is software that translates a program written in a high-level language like
C++ into machine language. The file containing the translated program is called the object
code of the program.

The compilation process


 The preprocessor removes comments and handles directives for source file inclusions,
definitions etc.
 The compiler translates source to assembly code
 The assembler creates object code, seen as a .OBJ file.
 The link editor combines any referenced functions from the libraries and makes an
executable code.

Source Code

Preprocessor

Compiler
Assembly Code

Assembler
Libraries
Object Code
Link Editor

Executable Code
Figure 1: Adopted from MIT OpenCourseWare

2. Library Files
C++ has a limited number of keywords, and depends on Library Files for its functionality.
This functionality is achieved by using library files also referred to as Header files. The
standard C++ library is therefore a collection of functions, constants, classes, objects and
templates that extends the C++ language providing basic functionality to perform several
tasks, like classes to interact with the operating system, data containers, manipulators to
operate with them and algorithms commonly needed.
The declarations of the different elements provided by the library are split in several headers
that shall be included in the code in order to have access to its components:

Example: # include “iostream” or #include <iostream>


 The standard input/output library is called iostream.
 The statement # include is termed as a preprocessor directive. Preprocessor directives
are statements that are processed before the program is compiled.
The #include statement is used to insert the header code so your program may use the
functions defined in the header file.
 Angled brackets are used to instruct the preprocessor to find the header files from the
standard header file directory.

In ANSI-C++ (1998), the way to include header files from the standard library has changed.
The standard specifies the following modification from the C way of including standard
header files:
 Header file names no longer maintain the .h extension typical of the C language and
of pre-standard C++ compilers, as in the case of stdio.h, stdlib.h, iostream.h,
etc. The use of the extension h is depreciated and files previously known as
iostream.h become iostream (without .h).
 Each header from the C Standard Library is included in the C++ Standard Library
under a different name, generated by removing the .h, and adding a „c‟ at the start,
for example time.h becomes ctime. This distinguished them from the new C++
exclusive header files that have the same name.
 All classes and functions defined in standard libraries are under the std namespace
instead of being global.

Since now classes and functions of the standard libraries are located within the std
namespace the C++ using directive is used so that these become usable in the same way they
were in pre-standard code.
For example, to be able to use all the standard classes of iostream we have to include
something similar to this:

#include <iostream>
using namespace std;

That would be equivalent to the old expression: #include <iostream.h> used prior to the
ANSI standard of 1998.
Nevertheless for compatibility with ANSI-C, the use of name.h way to include C header files
is allowed. Therefore, both following examples are valid and equivalent in a compiler which
fulfills ANSI-C++ specifications:

// ANSI C++ example // pre ANSI C++ example


// also valid under ANSI C++, but
#include <cstdio> //deprecated
using namespace std;
#include <stdio.h>
int main ()
{ int main ()
printf ("Hello World!"); {
return 0; printf ("Hello World!");
} return 0;
}
3. Preprocessor Directives
The preprocessor is a program that runs before the compiler. Its job is to handle directives
that control what source code the compiler see as input. Before the program is compiled, the
source code is scanned by a preprocessor to perform text substitution, and header file
inclusions. C++ supports inline functions, and constants, so is consequently more often used
just for header file inclusion and conditional compilation statements.

Preprocessor directives are preceded with a hash („#‟). The # should always be placed in the
first column of the line.
The following is a directive that causes the contents of the header file to be brought into the
current file, effectively replacing the directive line with the contents of that file.
#include <iostream>

The include directive instructs the preprocessor to copy contents of the specified file into the
program. Essentially, the preprocessor replaces the directive with the contents of the specified
file. The left and right angle brackets surrounding the file name indicate that this is a system
file and can be found in a special system directory. Any program that wishes to use the
iostream library to perform input and output must contain this directive and it must appear
before any code that uses the iostream library.

4. Comments
Comments are pieces of source code that are not translated by the compiler into executable
code. Their purpose is to provide an explanation or description of the program operation.
It is always useful to include comments that name the author of the program so that later on if
other programmers have questions about the program, they know who to ask.
There are two types of comments in C++: Block Comments, and In-Line Comments.

4.1. Block Comments


Block comments span several lines. The characters „/*‟ start a block comment, and the
characters „*/‟ end the block comment.
/*
This is a block comment. The body of the comment is placed over several lines. The
comment ends when the terminating characters are provided.
*/

4.2. In-Line Comments


An in-line comment is a comment that is on a single line. Inline comments do not require
termination characters, as they're automatically terminated at the end of the line. The
characters // are used to start an inline comment.
// This is an in-line comment

Note: Nested block comments are not allowed in C++. The following causes an error:
/*
Start of a block comment.
/* An illegal nested comment */
End of a block comment.
*/
Inline comments may be nested within block comments, or even inline comments.
/*
Start of a block comment.
// A legal inline nested // comment
End of a block comment.
*/

5. The main Function


Most C++ programs have one main () function, with the exception of Dynamic Link
Libraries (DLL's) in Windows. The main () function is the starting point of the program. The
ANSII C++ definition for declaring the main () function is either:
 int main() or
 int main(int argc, char **argv)

The second definition is used with Command Line Arguments and shall be covered later.
 The ’ínt’ keyword preceding main () means that the program should return an integer
(whole number) to the operating system, signifying success or failure. E.g. A return value
of zero indicates success. By definition the function main () always returns and integer
result.
 Each statement within the main function or any other functions should be tabbed in
(indented) to show the structure.
 The braces are used to group the statements within the function together.
In a standard C++ program, the function named main is the first function called when the
program is compiled and executed. The parenthesis after then function are used to delimit any
arguments to the function.
The following is the basic structure of a standard C++ source file.
// Welcome.cpp
//Displays the string Literal Welcome to Software Development with C++
//Author: You
// Date: Friday, February 20, 2015
#include <iostream>
using namespace std;
int main()
{
cout << “Welcome to Software Development with C++ “ << endl;
return 0;
}

 The first four lines of the above program are comments.


 The fifth line, #include <iostream>, is a preprocessor directive.
 The sixth line is the directive, using namespace std; this makes available all the library
functions, classes and objects defined by the standard C++ library. Compilers that strictly
conform to the standards require the use of this directive for all programs referring to
library classes, objects and functions.
 The seventh line of the program names the function and specifies the results the function
will return.
 Following the parentheses is „{„, a left brace character which much like the parentheses,
are used to group things. In this case the left brace and the right brace at the end of the
function group the program statements that make up the function.
 The function consists of two statements:
cout << “Welcome to Software Development with C++“ << endl;
return 0;
 In the first statement, the operand cout is an object whose definition together with
descriptions of operations on it are found in the file iostream. cout (Console Out) is an
output stream and it typically corresponds to the display.
 The second operand is a string literal. The << (insertion operator) inserts the string into the
named stream, i.e. Welcome to Software Development with C++ is sent to the display
(output console) the monitor.
 The third operand, endl is also part of the iostream library; it is called a manipulator i.e. a
value that can be inserted into a stream to cause some special action to take place. In this
case, the manipulator endl inserts a new line character in the output stream (so that the
next output will begin on a new line) and it forces all output that has been sent to the
display to be printed immediately.
 The second and final statement of the program is
return 0;
This statement ends the execution of function main, and control is returned to the code that
called main. This code does some cleanup (e.g., files are closed), and then control is returned
to the operating system.
Communication through the Console (Basic input /output, I/O)
The console is the basic interface of computers, normally it is the set composed of the
keyboard and the screen (also called the Visual Display Unit, VDU). The keyboard is
generally the standard input device and the screen the standard output device.

In the iostream C++ library, standard input and output operations for a program are supported
by two data streams:
 cin for input is the standard input stream and is normally assigned to the keyboard.
 cout for output is the standard output stream directed to the screen.
Additionally, cerr and clog have also been implemented – which are output streams
specially designed to display error messages. They can be redirected to the standard
output or to a log file.

By using these two streams the program is able to interact with the user by displaying
messages on the screen and receiving input from the keyboard.

Output (cout)
The cout stream is used in conjunction with the overloaded operator << (a pair of "less than"
signs).
cout << "Display this Message"; // prints Display this Message on screen
cout << 100; // prints number 100 on screen
cout << y; // prints the content of variable y on screen
The << operator is known as the insertion operator since it inserts the data that follows it into
the stream that precedes it. In the examples above it inserted the constant string Display
this message, the numerical constant 1o0 and the variable y into the output stream cout.
Notice that the first of the two sentences is enclosed between double quotes (") because it is a
string of characters. Whenever we want to use constant strings of characters we must enclose
them between double quotes (") so that they can be clearly distinguished from variables. For
example, these two sentences are very different:
cout << "Cplusplus"; // prints Cplusplus on screen
cout << Cplusplus; // prints the content of Cplusplus variable on
screen
The insertion operator (<<) may be used more than once in a same sentence:
cout << "Hello, " << "I am " << "a C++ sentence";
This statement will print the message Hello, I am a C++ sentence on the screen. The
utility of repeating the insertion operator (<<) is demonstrated when one wants to print out a
combination of variables and constants or more than one variable:
cout << "Hello, I am " << age << " years old and my zipcode is " <<
zipcode;
Suppose that the variable age contains the number 24 and the variable zipcode contains
90064, the output of the above statement will be:

Hello, I am 24 years old and my zipcode is 90064


It is important to notice that cout does not add a line break after its output unless we
explicitly indicate it, therefore, the following sentences:
cout << "This is a statement.";
cout << "This is another statement.";
will be shown followed in screen:
This is a statement. This is another statement.

though they have been written in two different calls to cout. So, in order to perform a line
break on output one must explicitly order it by inserting a new-line character that in C++ can
be written as \n:
cout << "First Paragraph.\n ";
cout << "Second Paragraph.\nThird paragraph.";
produces the following output:
First paragraph.
Second paragraph.
Third paragraph.

Additionally, to add a new-line, you may also use the endl manipulator. For example:
cout << "First paragraph." << endl;
cout << "Second paragraph." << endl;
would print out:
First paragraph.
Second paragraph.

Input (cin).
Handling the standard input in C++ is done by applying the overloaded operator of extraction
(>>) on the cin stream. This must be followed by the variable that will store the data that is
going to be read. For example:
int x;
cin >> x;
declares the variable x as an int and then waits for an input from cin (keyboard) in order to
store it in this integer variable.

cin can only process the input from the keyboard once the RETURN key has been pressed.
Therefore, even if you request a single character cin will not process the input until the user
presses RETURN once the character has been introduced.
You must always consider the type of the variable that you are using as a container with cin
extraction. If you request an integer you will get an integer, if you request a character you
will get a character and if you request a string of characters you will get a string of characters.
/******************************************************** */
/*VAT.cpp */
/*Computes VAT on purchases */
/*Author: You */
/* Date: Friday, February 20, 2015 */
/******************************************************** */
#include “iostream”
using namespace std;
int main ()
{
double price (0);
cout << “Enter the purchase price “;
cin >> price;
cout << “The VAT on $ “ << price << “ is ” <<endl
<< “$” << price*0.18 << endl;
return 0;
}

The user of a program may be one of the reasons that provoke errors even in the simplest
programs that use cin (like the one above). If you request for an integer value and the user
introduces a name (which is a string of characters), the result may cause your program to
malfunction since it is not what it was expecting from the user. So when you use the data
input provided by cin you will have to trust that the user of your program will be totally
cooperative and that he will not introduce his name when an integer value is requested.
cin can also be used to request more than one datum input from the user:
cin >> a >> b;

is equivalent to:
cin >> a;
cin >> b;

In both cases the user must give two data, one for variable a and another for variable b that
may be separated by any valid blank separator: a space, a tab character or a new line.
List of the standard C++ header files:
<algorithm> <bitset> <deque> <exception> <fstream> <functional>
<iomanip> <ios> <iosfwd> <iostream> <istream> <iterator>
<limits> <list> <locale> <map> <memory> <new> <numeric>
<ostream> <queue> <set> <sstream> <stack> <stdexcept>
<streambuf> <string> <typeinfo> <utility> <valarray> <vector>

List of the C header files included in ANSI-C++ with their new name and their
equivalents in ANSI-C:

ANSI-C++ ANSI-C

<cassert> <assert.h>

<cctype> <ctype.h>

<cerrno> <errno.h>

<cfloat> <float.h>

<ciso646> <iso646.h>

<climits> <limits.h>

<clocale> <locale.h>

<cmath> <math.h>

<csetjmp> <setjmp.h>

<csignal> <signal.h>

<cstdarg> <stdarg.h>

<cstddef> <stddef.h>

<cstdio> <stdio.h>

<cstdlib> <stdlib.h>

<cstring> <string.h>

<ctime> <time.h>

<cwchar> <wchar.h>

<cwtype> <wtype.h>

You might also like