C++ Language
tutorial for beginners
AMAIRI Moatez
Embedded Systems Engineerz
summary
introduction
• C ++ Language History
• Comparing C and C ++
• Key Features of C ++ Language
• The development environment
• Quality Criteria in Software Development
• Overview of object-oriented languages
Functions and use of C code in a C ++ program
Variables and Constants
Operators and control instructions
Pointers and references
summary
Functional programming: syntax
Basic syntax
Comment on the code
Principle of functions
Function input data
ReturnValues of Functions
Function arguments
Overloading names
Organizing C ++ applications
summary
THEVARIABLES
•Types of variables
• Scope of variables(Local variables, Global variables, Placement of variable declarations)
• Casting
• Manipulation of data
• Using constants
• Pointers
•The references
• Simple arithmetic operations
summary
Conversions to C ++
• Presentation
• const_cast
• static_cast
• reinterpret_cast
• dynamic_cast
Structured Programming
• structures
• Memory Management
• The standard C language library
summary
Object Oriented Programming
• Creating Classes and Objects
• Class members and methods (virtual / virtual)
• Derivation and inheritance (single / multiple)
Other specific aspects:
• overloads
• The chains
• Data Structures and Algorithms
summary
The exceptions
• Approche de la gestion d’exceptions
• Les exceptions (notamment exceptions imbriquées)
• Les classes d’exception applicatives
• Traitement des erreurs dans les programmes / en C++
Introduction ( C ++ Language History )
In the early 1970s, Dennis Ritchie of Bell Laboratories was engaged in a project to develop a new operating system.
Ritchie discovered that in order to accomplish his task he needed the use of a programming language that was concise
and that produced compact and speedy programs.This need led Ritchie to develop the programming language called C.
In the early 1980's, also at Bell Laboratories, another programming language was created which was based upon the
C language. This new language was developed by Bjarne Stroustrup and was called C++. Stroustrup states that the
purpose of C++ is to make writing good programs easier and more pleasant for the individual programmer. When he
designed C++, he added OOP (Object Oriented Programming) features to C without significantly changing the C
component. Thus C++ is a "relative" (called a superset) of C, meaning that any valid C program is also a valid C++
program.
Introduction ( Comparing C and C ++ )
Difference between C and C++
C C++
C was developed by Dennis Ritchie between
1969 and 1973 at AT&T Bell Labs.
C++ was developed by Bjarne Stroustrup in 1979
with C++'s predecessor "C with Classes".
When compared to C++,C is a subset of C++. C++ is a superset of C. C++ can run most of C code
while C cannot runC++ code.
C supports procedural programming paradigm
for code development.
C++ supports both procedural and object
oriented programming paradigms; therefore C++
is also called a hybrid language.
C does not support object oriented
programming; therefore it has no support for
polymorphism, encapsulation, and inheritance.
Being an object oriented programming language
C++ supports polymorphism, encapsulation, and
inheritance.
In C (because it is a procedural programming
language), data and functions are separate and
free entities.
In C++ (when it is used as object oriented
programming language), data and functions are
encapsulated together in form of an object. For
creating objects class provides a blueprint of
structure of the object.
In C, data are free entities and can be manipulated by outside code.
This is becauseC does not support information hiding.
In C++, Encapsulation hides the data to ensure that data structures and
operators are used as intended.
C, being a procedural programming, it is a function driven language. While, C++, being an object oriented programming, it is an object driven
language.
C does not support function and operator overloading. C++ supports both function and operator overloading.
C does not allow functions to be defined inside structures. In C++, functions can be used inside a structure.
C does not have namespace feature. C++ uses NAMESPACE which avoid name collisions.
A namespace is a declarative region that provides a scope to the identifiers
(the names of types, functions, variables, etc) inside it. Namespaces are
used to organize code into logical groups and to prevent name collisions
that can occur especially when your code base includes multiple libraries.
All identifiers at namespace scope are visible to one another without
qualification. Identifiers outside the namespace can access the members
by using the fully qualified name for each identifier.
C uses functions for input/output. For example scanf and printf. C++ uses objects for input output. For example cinand cout.
C does not support reference variables. C++ supports reference variables.
C has no support for virtual and friend functions. C++ supports virtual and friend functions.
C provides malloc() and calloc() functions for dynamic memory
allocation, and free() for memory de-allocation.
C++ provides new operator for memory allocation and delete operator for
memory de-allocation.
C does not provide direct support for error handling (also called
exception handling)
C++ provides support for exception handling. Exceptions are used for
"hard" errors that make the code incorrect.
Introduction ( Comparing C and C ++ )
Introduction (Key Features of C ++ Language)
- Platform dependent
A language is said to be platform dependent whenever the
program is execute in the same operating system where that
was developed and compiled but not run and execute on other
operating system. C++ is platform dependent language.
Introduction (Key Features of C ++ Language)
- Portability
It is the concept of carrying the instruction from one system to another system. In C++ Language
.cpp file contain source code, we can edit also this code. .exe file contain application, only we can
execute this file.When we write and compile any C++ program on window operating system that
program easily run on other window based system.
Introduction (Key Features of C ++ Language)
- Object oriented Programming language
This main advantage of C++ is, it is object oriented programming language. It follow concept of
oops like polymorphism, inheritance, encapsulation, abstraction.
- Compiler based
C++ is a compiler based programming language that means without compilation no C++
program can be executed. First we need compiler to compile our program and then execute.
- Efficient use of pointers
Pointers is a variable which hold the address of another variable, pointer directly direct access to
memory address of any variable due to this performance of application is improve. In C++
language also concept of pointer are available.
- It is easy to maintain and modify existing code as new objects can be created with small
differences to existing ones.
- Much suitable for large projects.
NetBeans IDE includes project types for C and C++ and appropriate project templates.
You can work with and create C/C++ applications with dynamic and static libraries
https://netbeans.org/downloads/index.html
Introduction (The development environment)
IT Software Quality (CISQ)
Introduction (Quality Criteria in Software Development)
Security
A measure of the likelihood of potential security breaches due to poor coding practices and architecture.
This quantifies the risk of encountering critical vulnerabilities that damage the business.
Efficiency
The source code and software architecture attributes are the elements that ensure high performance
once the application is in run-time mode. Efficiency is especially important for applications in high
execution speed environments such as algorithmic or transactional processing where performance and
scalability are paramount. An analysis of source code efficiency and scalability provides a clear picture of
the latent business risks and the harm they can cause to customer satisfaction due to response-time
degradation.
Reliability
An attribute of resiliency and structural solidity. Reliability measures the level of risk and the
likelihood of potential application failures. It also measures the defects injected due to modifications
made to the software (its "stability" as termed by ISO).The goal for checking and monitoring
Reliability is to reduce and prevent application downtime, application outages and errors that
directly affect users, and enhance the image of IT and its impact on a company's business
performance.
Maintainability
Maintainability includes the notion of adaptability, portability and transferability (from one
development team to another). Measuring and monitoring maintainability is a must for mission-
critical applications where change is driven by tight time-to-market schedules and where it is
important for IT to remain responsive to business-driven changes. It is also essential to keep
maintenance costs under control.
IT Software Quality (CISQ)
Introduction (Quality Criteria in Software Development)
Object-oriented programming (OOP) is a programming paradigm based on the concept of
"objects", which may contain data, in the form of fields, often known as attributes; and code,
in the form of procedures, often known as methods. A feature of objects is that an object's
procedures can access
Introduction (Overview of object-oriented languages)
Functions and use of C code in a C ++ program
The general format for a prototype is simple:
return-type function_name( arg_type arg1, ..., arg_type argN );
arg_type just means the type for each argument -- for instance, an int, a float, or a char. It's exactly
the same thing as what you would put if you were declaring a variable.
There can be more than one argument passed to a function or none at all (where the parentheses are
empty), and it does not have to return a value. Functions that do not return values have a return type
of void. Let's look at a function prototype:
int mult( int x, int y );
Let's look at an example program:
Functions and use of C code in a C ++ program
#include <iostream>
using namespace std;
int mult ( int x, int y );
int main()
{
int x;
int y;
cout<<"Please input two numbers to be multiplied: ";
cin>> x >> y;
cin.ignore();
cout<<"The product of your two numbers is "<< mult ( x, y ) <<"n";
cin.get();
}
int mult ( int x, int y )
{
return x * y;
}
C programming does not allow to return an entire array as an argument to a function. However, you
can return a pointer to an array by specifying the array's name without an index.
Functions and use of C code in a C ++ program
If you want to return a single-dimension array from a function, you would have to declare a
function returning a pointer as in the following example −
int * myFunction() {
.
.
.
}
#include <stdio.h>
int * getRandom( ) {
static int r[10];
int i;
srand( (unsigned)time( NULL ) );
for ( i = 0; i < 10; ++i) {
r[i] = rand();
printf( "r[%d] = %dn", i, r[i]);
}
return r;
}
int main () {
int *p;
int i;
p = getRandom();
for ( i = 0; i < 10; i++ ) {
printf( "*(p + %d) : %dn", i, *(p + i));
}
return 0;
}
Functions and use of C code in a C ++ program
Let's look at an example program:
Variables and Constants
What Is a Variable?
From a programmer's point of view, a variable is a location in your computer's memory in which
you can store a value and from which you can later retrieve that value
signed and unsigned
In addition, all these types come in two varieties: signed and unsigned. Sometimes you need
negative numbers, and sometimes you don't. Integers (short and long) without the word
"unsigned" are assumed to be signed. signed integers are either negative or positive. unsigned
integers are always positive.
Type Size Values
unsigned short int 2 bytes 0 to 65,535
short int 2 bytes –32,768 to 32,767
unsigned long int 4 bytes 0 to 4,294,967,295
long int 4 bytes –2,147,483,648 to 2,147,483,647
int 4 bytes –2,147,483,648 to 2,147,483,647
unsigned int 4 bytes 0 to 4,294,967,295
char 1 byte -256 character values
bool 1 byte true or false
float 4 bytes 1.2e–38 to 3.4e38
double 8 bytes 2.2e–308 to 1.8e308
Variables and Constants
Defining Constants
Variables and Constants
There are two simple ways in C++ to define
constants:
•Using #define preprocessor.
•Using const keyword.
The #define Preprocessor
#define identifier value
Following example explains it in detail:
#include <iostream>
using namespace std;
#define LENGTH 10
#define WIDTH 5
#define NEWLINE 'n'
int main() {
int area;
area = LENGTH * WIDTH;
cout << area;
cout << NEWLINE;
return 0;
}
The const Keyword
Variables and Constants
You can use const prefix to declare constants with a specific type as follows:
const type variable = value; #include <iostream>
using namespace std;
int main() {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = 'n';
int area;
area = LENGTH * WIDTH;
cout << area;
cout << NEWLINE;
return 0;
}
Operators and control instructions
The if keyword is used to execute a statement or block only if a condition is fulfilled. Its form is:
if (condition) statement
Iteration structures (loops)
Loops have as purpose to repeat a statement a certain number of times or while a condition is
fulfilled.
The while loop
Its format is:
while (expression) statement
#include <iostream>
using namespace std;
int main ()
{
int n;
cout << "Enter the starting number > ";
cin >> n;
while (n>0) {
cout << n << ", ";
--n;
}
cout << "FIRE!n";
return 0;
}
Operators and control instructions
The do-while loop
Its format is:
do statement while (condition);
The for loop
Its format is:
for (initialization; condition; increase) statement;
// number echoer
#include <iostream>
using namespace std;
int main ()
{
unsigned long n;
do {
cout << "Enter number (0 to end): ";
cin >> n;
cout << "You entered: " << n << "n";
} while (n != 0);
return 0;
}
// countdown using a for loop
#include <iostream>
using namespace std;
int main ()
{
for (int n=10; n>0; n--) {
cout << n << ", ";
}
cout << "FIRE!n";
return 0;
}
Operators and control instructions
for ( n=0, i=100 ; n!=i ; n++, i-- )
{
// whatever here...
}
This loop will execute for 50 times if neither n or i are modified within the loop
Jump statements.
The break statement
Using break we can leave a loop even if the
condition for its end is not fulfilled. It can be used to
end an infinite loop, or to force it to end before its
natural end. For example, we are going to stop the
count down before its natural end (maybe because
of an engine check failure?):
// break loop example
#include <iostream>
using namespace std;
int main ()
{
int n;
for (n=10; n>0; n--)
{
cout << n << ", ";
if (n==3)
{
cout << "countdown aborted!";
break;
}
}
return 0;
}
Operators and control instructions
10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!
Operators and control instructions
The continue statement
The continue statement causes the program to skip the rest of the loop in the current iteration as if the end
of the statement block had been reached, causing it to jump to the start of the following iteration. For
example, we are going to skip the number 5 in our countdown:
// continue loop example
#include <iostream>
using namespace std;
int main ()
{
for (int n=10; n>0; n--) {
if (n==5) continue;
cout << n << ", ";
}
cout << "FIRE!n";
return 0;
}
10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE!
Operators and control instructions
The goto statement
goto allows to make an absolute jump to another point in the program.You should use this feature with
caution since its execution causes an unconditional jump ignoring any type of nesting limitations.
The destination point is identified by a label, which is then used as an argument for the goto statement. A
label is made of a valid identifier followed by a colon (:).
// goto loop example
#include <iostream>
using namespace std;
int main ()
{
int n=10;
loop:
cout << n << ", ";
n--;
if (n>0) goto loop;
cout << "FIRE!n";
return 0;
} 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
The selective structure: switch.
The syntax of the switch statement is a bit peculiar. Its objective is to check several possible constant
values for an expression. Something similar to what we did at the beginning of this section with the
concatenation of several if and else if instructions. Its form is the following:
switch (expression)
{
case constant1:
group of statements 1;
break;
case constant2:
group of statements 2;
break;
.
.
default:
default group of statements
}
Operators and control instructions
Pointers and references
The following diagram illustrate the relationship between computers' memory address and content; and
variable's name, type and value used by the programmers.
Declaring Pointers
Pointers must be declared before they can be used, just like a normal variable.The syntax of declaring a pointer is to
place a * in front of the name. A pointer is associated with a type (such as int and double) too.
type* ptr;
Take note that you need to place a * in front of each pointer variable, in other words, * applies only to the name that
followed.The * in the declaration statement is not an operator, but indicates that the name followed is a pointer
variable. For example,
int *p1, *p2, i; // p1 and p2 are int pointers. i is an int
int* p1, p2, i; // p1 is a int pointer, p2 and i are int
int * p1, * p2, i; // p1 and p2 are int pointers, i is an int
Pointers and references
end of the part 1

Part 1

  • 1.
    C++ Language tutorial forbeginners AMAIRI Moatez Embedded Systems Engineerz
  • 2.
    summary introduction • C ++Language History • Comparing C and C ++ • Key Features of C ++ Language • The development environment • Quality Criteria in Software Development • Overview of object-oriented languages Functions and use of C code in a C ++ program Variables and Constants Operators and control instructions Pointers and references
  • 3.
    summary Functional programming: syntax Basicsyntax Comment on the code Principle of functions Function input data ReturnValues of Functions Function arguments Overloading names Organizing C ++ applications
  • 4.
    summary THEVARIABLES •Types of variables •Scope of variables(Local variables, Global variables, Placement of variable declarations) • Casting • Manipulation of data • Using constants • Pointers •The references • Simple arithmetic operations
  • 5.
    summary Conversions to C++ • Presentation • const_cast • static_cast • reinterpret_cast • dynamic_cast Structured Programming • structures • Memory Management • The standard C language library
  • 6.
    summary Object Oriented Programming •Creating Classes and Objects • Class members and methods (virtual / virtual) • Derivation and inheritance (single / multiple) Other specific aspects: • overloads • The chains • Data Structures and Algorithms
  • 7.
    summary The exceptions • Approchede la gestion d’exceptions • Les exceptions (notamment exceptions imbriquées) • Les classes d’exception applicatives • Traitement des erreurs dans les programmes / en C++
  • 8.
    Introduction ( C++ Language History ) In the early 1970s, Dennis Ritchie of Bell Laboratories was engaged in a project to develop a new operating system. Ritchie discovered that in order to accomplish his task he needed the use of a programming language that was concise and that produced compact and speedy programs.This need led Ritchie to develop the programming language called C. In the early 1980's, also at Bell Laboratories, another programming language was created which was based upon the C language. This new language was developed by Bjarne Stroustrup and was called C++. Stroustrup states that the purpose of C++ is to make writing good programs easier and more pleasant for the individual programmer. When he designed C++, he added OOP (Object Oriented Programming) features to C without significantly changing the C component. Thus C++ is a "relative" (called a superset) of C, meaning that any valid C program is also a valid C++ program.
  • 9.
    Introduction ( ComparingC and C ++ ) Difference between C and C++ C C++ C was developed by Dennis Ritchie between 1969 and 1973 at AT&T Bell Labs. C++ was developed by Bjarne Stroustrup in 1979 with C++'s predecessor "C with Classes". When compared to C++,C is a subset of C++. C++ is a superset of C. C++ can run most of C code while C cannot runC++ code. C supports procedural programming paradigm for code development. C++ supports both procedural and object oriented programming paradigms; therefore C++ is also called a hybrid language. C does not support object oriented programming; therefore it has no support for polymorphism, encapsulation, and inheritance. Being an object oriented programming language C++ supports polymorphism, encapsulation, and inheritance. In C (because it is a procedural programming language), data and functions are separate and free entities. In C++ (when it is used as object oriented programming language), data and functions are encapsulated together in form of an object. For creating objects class provides a blueprint of structure of the object.
  • 10.
    In C, dataare free entities and can be manipulated by outside code. This is becauseC does not support information hiding. In C++, Encapsulation hides the data to ensure that data structures and operators are used as intended. C, being a procedural programming, it is a function driven language. While, C++, being an object oriented programming, it is an object driven language. C does not support function and operator overloading. C++ supports both function and operator overloading. C does not allow functions to be defined inside structures. In C++, functions can be used inside a structure. C does not have namespace feature. C++ uses NAMESPACE which avoid name collisions. A namespace is a declarative region that provides a scope to the identifiers (the names of types, functions, variables, etc) inside it. Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries. All identifiers at namespace scope are visible to one another without qualification. Identifiers outside the namespace can access the members by using the fully qualified name for each identifier. C uses functions for input/output. For example scanf and printf. C++ uses objects for input output. For example cinand cout. C does not support reference variables. C++ supports reference variables. C has no support for virtual and friend functions. C++ supports virtual and friend functions. C provides malloc() and calloc() functions for dynamic memory allocation, and free() for memory de-allocation. C++ provides new operator for memory allocation and delete operator for memory de-allocation. C does not provide direct support for error handling (also called exception handling) C++ provides support for exception handling. Exceptions are used for "hard" errors that make the code incorrect. Introduction ( Comparing C and C ++ )
  • 11.
    Introduction (Key Featuresof C ++ Language) - Platform dependent A language is said to be platform dependent whenever the program is execute in the same operating system where that was developed and compiled but not run and execute on other operating system. C++ is platform dependent language.
  • 12.
    Introduction (Key Featuresof C ++ Language) - Portability It is the concept of carrying the instruction from one system to another system. In C++ Language .cpp file contain source code, we can edit also this code. .exe file contain application, only we can execute this file.When we write and compile any C++ program on window operating system that program easily run on other window based system.
  • 13.
    Introduction (Key Featuresof C ++ Language) - Object oriented Programming language This main advantage of C++ is, it is object oriented programming language. It follow concept of oops like polymorphism, inheritance, encapsulation, abstraction. - Compiler based C++ is a compiler based programming language that means without compilation no C++ program can be executed. First we need compiler to compile our program and then execute. - Efficient use of pointers Pointers is a variable which hold the address of another variable, pointer directly direct access to memory address of any variable due to this performance of application is improve. In C++ language also concept of pointer are available. - It is easy to maintain and modify existing code as new objects can be created with small differences to existing ones. - Much suitable for large projects.
  • 14.
    NetBeans IDE includesproject types for C and C++ and appropriate project templates. You can work with and create C/C++ applications with dynamic and static libraries https://netbeans.org/downloads/index.html Introduction (The development environment)
  • 15.
    IT Software Quality(CISQ) Introduction (Quality Criteria in Software Development) Security A measure of the likelihood of potential security breaches due to poor coding practices and architecture. This quantifies the risk of encountering critical vulnerabilities that damage the business. Efficiency The source code and software architecture attributes are the elements that ensure high performance once the application is in run-time mode. Efficiency is especially important for applications in high execution speed environments such as algorithmic or transactional processing where performance and scalability are paramount. An analysis of source code efficiency and scalability provides a clear picture of the latent business risks and the harm they can cause to customer satisfaction due to response-time degradation.
  • 16.
    Reliability An attribute ofresiliency and structural solidity. Reliability measures the level of risk and the likelihood of potential application failures. It also measures the defects injected due to modifications made to the software (its "stability" as termed by ISO).The goal for checking and monitoring Reliability is to reduce and prevent application downtime, application outages and errors that directly affect users, and enhance the image of IT and its impact on a company's business performance. Maintainability Maintainability includes the notion of adaptability, portability and transferability (from one development team to another). Measuring and monitoring maintainability is a must for mission- critical applications where change is driven by tight time-to-market schedules and where it is important for IT to remain responsive to business-driven changes. It is also essential to keep maintenance costs under control. IT Software Quality (CISQ) Introduction (Quality Criteria in Software Development)
  • 17.
    Object-oriented programming (OOP)is a programming paradigm based on the concept of "objects", which may contain data, in the form of fields, often known as attributes; and code, in the form of procedures, often known as methods. A feature of objects is that an object's procedures can access Introduction (Overview of object-oriented languages)
  • 18.
    Functions and useof C code in a C ++ program The general format for a prototype is simple: return-type function_name( arg_type arg1, ..., arg_type argN ); arg_type just means the type for each argument -- for instance, an int, a float, or a char. It's exactly the same thing as what you would put if you were declaring a variable. There can be more than one argument passed to a function or none at all (where the parentheses are empty), and it does not have to return a value. Functions that do not return values have a return type of void. Let's look at a function prototype: int mult( int x, int y );
  • 19.
    Let's look atan example program: Functions and use of C code in a C ++ program #include <iostream> using namespace std; int mult ( int x, int y ); int main() { int x; int y; cout<<"Please input two numbers to be multiplied: "; cin>> x >> y; cin.ignore(); cout<<"The product of your two numbers is "<< mult ( x, y ) <<"n"; cin.get(); } int mult ( int x, int y ) { return x * y; }
  • 20.
    C programming doesnot allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index. Functions and use of C code in a C ++ program If you want to return a single-dimension array from a function, you would have to declare a function returning a pointer as in the following example − int * myFunction() { . . . }
  • 21.
    #include <stdio.h> int *getRandom( ) { static int r[10]; int i; srand( (unsigned)time( NULL ) ); for ( i = 0; i < 10; ++i) { r[i] = rand(); printf( "r[%d] = %dn", i, r[i]); } return r; } int main () { int *p; int i; p = getRandom(); for ( i = 0; i < 10; i++ ) { printf( "*(p + %d) : %dn", i, *(p + i)); } return 0; } Functions and use of C code in a C ++ program Let's look at an example program:
  • 22.
    Variables and Constants WhatIs a Variable? From a programmer's point of view, a variable is a location in your computer's memory in which you can store a value and from which you can later retrieve that value signed and unsigned In addition, all these types come in two varieties: signed and unsigned. Sometimes you need negative numbers, and sometimes you don't. Integers (short and long) without the word "unsigned" are assumed to be signed. signed integers are either negative or positive. unsigned integers are always positive.
  • 23.
    Type Size Values unsignedshort int 2 bytes 0 to 65,535 short int 2 bytes –32,768 to 32,767 unsigned long int 4 bytes 0 to 4,294,967,295 long int 4 bytes –2,147,483,648 to 2,147,483,647 int 4 bytes –2,147,483,648 to 2,147,483,647 unsigned int 4 bytes 0 to 4,294,967,295 char 1 byte -256 character values bool 1 byte true or false float 4 bytes 1.2e–38 to 3.4e38 double 8 bytes 2.2e–308 to 1.8e308 Variables and Constants
  • 24.
    Defining Constants Variables andConstants There are two simple ways in C++ to define constants: •Using #define preprocessor. •Using const keyword. The #define Preprocessor #define identifier value Following example explains it in detail: #include <iostream> using namespace std; #define LENGTH 10 #define WIDTH 5 #define NEWLINE 'n' int main() { int area; area = LENGTH * WIDTH; cout << area; cout << NEWLINE; return 0; }
  • 25.
    The const Keyword Variablesand Constants You can use const prefix to declare constants with a specific type as follows: const type variable = value; #include <iostream> using namespace std; int main() { const int LENGTH = 10; const int WIDTH = 5; const char NEWLINE = 'n'; int area; area = LENGTH * WIDTH; cout << area; cout << NEWLINE; return 0; }
  • 26.
    Operators and controlinstructions The if keyword is used to execute a statement or block only if a condition is fulfilled. Its form is: if (condition) statement Iteration structures (loops) Loops have as purpose to repeat a statement a certain number of times or while a condition is fulfilled. The while loop Its format is: while (expression) statement #include <iostream> using namespace std; int main () { int n; cout << "Enter the starting number > "; cin >> n; while (n>0) { cout << n << ", "; --n; } cout << "FIRE!n"; return 0; }
  • 27.
    Operators and controlinstructions The do-while loop Its format is: do statement while (condition); The for loop Its format is: for (initialization; condition; increase) statement; // number echoer #include <iostream> using namespace std; int main () { unsigned long n; do { cout << "Enter number (0 to end): "; cin >> n; cout << "You entered: " << n << "n"; } while (n != 0); return 0; } // countdown using a for loop #include <iostream> using namespace std; int main () { for (int n=10; n>0; n--) { cout << n << ", "; } cout << "FIRE!n"; return 0; }
  • 28.
    Operators and controlinstructions for ( n=0, i=100 ; n!=i ; n++, i-- ) { // whatever here... } This loop will execute for 50 times if neither n or i are modified within the loop
  • 29.
    Jump statements. The breakstatement Using break we can leave a loop even if the condition for its end is not fulfilled. It can be used to end an infinite loop, or to force it to end before its natural end. For example, we are going to stop the count down before its natural end (maybe because of an engine check failure?): // break loop example #include <iostream> using namespace std; int main () { int n; for (n=10; n>0; n--) { cout << n << ", "; if (n==3) { cout << "countdown aborted!"; break; } } return 0; } Operators and control instructions 10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!
  • 30.
    Operators and controlinstructions The continue statement The continue statement causes the program to skip the rest of the loop in the current iteration as if the end of the statement block had been reached, causing it to jump to the start of the following iteration. For example, we are going to skip the number 5 in our countdown: // continue loop example #include <iostream> using namespace std; int main () { for (int n=10; n>0; n--) { if (n==5) continue; cout << n << ", "; } cout << "FIRE!n"; return 0; } 10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE!
  • 31.
    Operators and controlinstructions The goto statement goto allows to make an absolute jump to another point in the program.You should use this feature with caution since its execution causes an unconditional jump ignoring any type of nesting limitations. The destination point is identified by a label, which is then used as an argument for the goto statement. A label is made of a valid identifier followed by a colon (:). // goto loop example #include <iostream> using namespace std; int main () { int n=10; loop: cout << n << ", "; n--; if (n>0) goto loop; cout << "FIRE!n"; return 0; } 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
  • 32.
    The selective structure:switch. The syntax of the switch statement is a bit peculiar. Its objective is to check several possible constant values for an expression. Something similar to what we did at the beginning of this section with the concatenation of several if and else if instructions. Its form is the following: switch (expression) { case constant1: group of statements 1; break; case constant2: group of statements 2; break; . . default: default group of statements } Operators and control instructions
  • 33.
    Pointers and references Thefollowing diagram illustrate the relationship between computers' memory address and content; and variable's name, type and value used by the programmers.
  • 34.
    Declaring Pointers Pointers mustbe declared before they can be used, just like a normal variable.The syntax of declaring a pointer is to place a * in front of the name. A pointer is associated with a type (such as int and double) too. type* ptr; Take note that you need to place a * in front of each pointer variable, in other words, * applies only to the name that followed.The * in the declaration statement is not an operator, but indicates that the name followed is a pointer variable. For example, int *p1, *p2, i; // p1 and p2 are int pointers. i is an int int* p1, p2, i; // p1 is a int pointer, p2 and i are int int * p1, * p2, i; // p1 and p2 are int pointers, i is an int Pointers and references
  • 35.
    end of thepart 1