c to C++
Many similar code
but C++ is not C, as C is not C++ !
Let's get into these differences ...
summary
Strings
Functions
Arrays
Pointers
New types: string
C++ has a new type "string" to put text in it
It works fine with cin and cout
NEW TYPEs: string
Using "string" example
#include <iostream>
using namespace std;
int main()
{
string name("");
cout << "What is your name?" << endl;
cin >> name;
cout << "Hello " << name << ", how are you today?" << endl;
return 0;
}
Functions
Here is the default code proposed by Code::Blocks when creating a new C++ project. This code already contain a function: main()
#include <iostream>
using namespace std;
int main() // Every C++ programs start by running this function
{
cout << "Hello world!" << endl;
return0;
}
functions
Cut the code in smaller parts
Use some instructions several times
A function:
- Can receive datas (arguments)
- Process its instructions
- Return a value as a result
Functions: skeleton
type functionName(arguments)
{
[...]
instructions;
[...]
return value;
}
Functions: add()
int add(int a, int b)
{
int result;
result = a + b;
return result;
}
int main()
{
cout << "Write a first integer: "; cin >> int1;
cout << "Write a second integer: "; cin >> int2;
int int3 = add(int1, int2);
cout << int1 << "+" << int2 << "=" << int3 << endl;
return 0;
}
Functions: void
"void" allows the creation of a function
without a return value
void sayHello()
{
cout << "Hello!" << endl;
}
Functions: calls
Call by value:
data copied into a local variable
Call by reference:
local variable point to the original data
Functions: call by value
int addTwo(int a)
{
a = a + 2;
return a;
}
int main()
{
int number(6), result;
result = addTwo(number);
cout << "number=" << number << " and result=" << result << endl;
return 0;
}
// number = 6
// result = 8
Functions: call by reference
int addTwo(int& a)
{
a = a + 2;
return a;
}
int main()
{
int number(6), result;
result = addTwo(number);
cout << "number=" << number << " and result=" << result << endl;
return 0;
}
// number = 8
// result = 8
FUNCTIONS: CALL BY CONST REFERENCE
Faster: avoid copy
Safer: prevent modifications
void copyBook(string text) // long to copy
{}
void copyBook2(string& text) // can modify original text
{}
void copyBook3(string const& text) // fast copy and read-only
{}
Functions: ORDERING the code
Every functions in one file ...
BAD HABIT !!!
Sort the code using several files
Functions: ordering the code
As an example, let's group all the mathematics functions.
2 files are needed:
- math.h (header file) containing functions prototypes
- math.cpp (source file) containing functions implementations
functions: ORDERING THE CODE
math.h
#ifndef MATH_H_INCLUDED // Ensure to include this file only once
#define MATH_H_INCLUDED // in the compilation process
// Add 2 numbers and return their sum
int add(int a, int b);
// Take number as argument and return number + 2
int addTwo(int a);
#endif
Advice: always comment the aim of the functions
functions: ORDERING THE CODE
math.cpp
#include "math.h" // Link the header
int add(int a, int b)
{
int result;
result = a + b;
return result;
}
int addTwo(int a)
{
a = a + 2;
return a;
}
Functions: ORDERING THE CODE
main.cpp
#include <iostream>
#include "math.h" // Link the functions of math files
int main()
{
int number;
cout << "Enter an integer: "; cin >> number;
addTwo(number);
cout << "Your number + 2 = " << number << endl;
return 0;
}
Arrays
Group datas of same type together
Static arrays
Dynamic arrays
Multidimensional array
Arrays: static
The size of the array is known:
it book the exact memory space
Skeleton
Example: declare an array of 5 classes
int const numberOfClasses(5); // The size of the array is known
string classes[numberOfClasses];
ARRAYS: STATIC
Fill the array
string classes[5];
classes[0] = "B1"; // Arrays starts with the index 0
classes[1] = "B2";
classes[2] = "B3";
classes[3] = "M1";
classes[4] = "M2";
ARRAYS: STATIC
Read a value
cout << "The class for B2 students is: " << classes[1] << endl;
Run through all the array
for(int i=0; i<numberOfClasses; i++) // numberOfClasses = 5
{
cout << classes[i] << endl;
}
Arrays: dynamic
The size of the array can change
#include <vector> // Do not forget to include the "vector" library!
Skeleton
vector<type> name(initialSize, defaultValue);
Examples
vector<double> scores;
vector<string> students(5);
vector<string> teachers(10, "no name");
ARRAYS: DYNAMIC
Fill the array
vector<string> students(5, "no name");
students[0] = "Justin BIEBER";
students[1] = "Bruce LEE";
students[2] = "Jack JOHNS";
Read it
cout << students[1] << endl; // Display Bruce LEE
for (int i=0; i<students.size(); i++) //size() returns the array size
{
cout << students[i] << endl;
} // Display all the students names
arrays: Dynamic
Add a value at the end of the array
vector<double> scores; // Declare an empty array
scores.push_back(18);
scores.push_back(11);
for(int i=0; i<scores.size(); i++) { cout << scores[i] << endl; }
Result:
arrays: Dynamic
Remove the last value of the array
vector<double> scores; // Declare an empty array
scores.push_back(18); // Add the value 18
scores.push_back(11); // Add the value 11
scores.pop_back(); // Remove the last value of the array
for(int i=0; i<scores.size(); i++) { cout << scores[i] << endl; }
Result:
Arrays: multidimensional
An array of arrays
Skeleton
type name[sizeA][sizeB]...[sizeN];
Example
int const sizeX(5);
int const sizeY(4);
int scores[sizeX][sizeY];
Exercise
Write a program that asks the user to type 10 integers of an array.
The program must output the largest element in the array,
and the index at which that element was found (if the largest element appear several times, output all its indexes).
POINTERS
Each memory space in a computer can contain only
one variable, and has an address
A variable can be accessed
- by its name
- by its address
int myAge(30);
cout << "The value of myAge is: " << myAge << endl;
cout << "The address of myAge is: " << &myAge << endl;
Pointers
How to record an address and access to its value?
Using a pointer!
A pointer is a variable containing the address of another variable
Pointers: Declaration
Skeleton
"type" must be the same type as the variable pointed to
Examples
int *p1;
double *p2;
sting *p3;
unsigned int *p4;
vector<string> *p5;
Pointers: declaration
ATTENTION !!!
If the pointer does not point to any known address
DANGER -> it could point to a system variable
Prevention
Always give the value 0 to the pointer when declaring it
Example
POINTERS: INITIALIZATION
Store an address into the pointer
int myAge(30);
int *myPointer(0);
myPointer = &myAge;
POINTER: USE
Display its content (an address)
cout << myPointer << endl; // Output 0x1ab23c4d for example
Display the value pointed to
cout << *myPointer << endl; // Output 30