/*
- Pointers
- Array allocation
- Arguments passing
by Jeff Souza
*/
#include <iostream>
using namespace std;
void pointers();
void arrays();
void arguments();
void swapV(int x, int y);
void swapR(int& x, int& y);
int main() {
//Pointers
pointers();
//Allocating Arrays
//arrays();
//Argument passing
//arguments();
return 0;
}
// This function shows how to define and
// use pointers and their operations
void pointers() {
int *pt_int1, *pt_int2;
float *pt_float;
int a = 7, b = 27;
float x = 1.2345, y = 32.14;
cout << "\n -------------------\n";
cout << "|
Pointers |\n";
cout << " -------------------\n\n";
pt_int1 = &a;
*pt_int1 += b;
cout << "A now has the value of " << *pt_int1
<< "\n";
pt_float = &x;
y += 5 * (*pt_float);
cout << "Y now has the value of " << y
<< "\n";
pt_int2 = pt_int1;
a = 123;
cout << "Pt_int2 in pointing to a variable with
value " << *pt_int2 << "\n\n";
cout << "Pt_int1 in pointing to position " <<
pt_int1 << " in memory.\n";
cout << "Pt_int2 in pointing to position " <<
pt_int2 << " in memory.\n";
cout << "Pt_float in pointing to position " <<
pt_float << " in memory.\n\n";
}
// This function demonstrates three different
// methods to allocate arrays in C++
// - Direct static allocation
// - Static allocation with constant
// - Dynamic allocation with pointer and variable
void arrays() {
const int num_elements_const = 100;
int num_elements_variable;
cout << "\n -------------------\n";
cout << "|
Arrays
|\n";
cout << " -------------------\n\n";
// static allocation
int array1[100];
cout << "Array1 allocated\n";
// static allocation with constant
int array2[num_elements_const];
cout << "Array2 allocated\n";
// dynamic allocation with pointer and variable
cout << "Type the number of elements for array3 : ";
cin >> num_elements_variable;
int *array4;
array4 = new int[num_elements_variable];
cout << "Array3 allocated with " <<
num_elements_variable << " positions.\n";
// don't forget to destroy this array after use
delete[] array4;
}
// This function is designed to make use of
// two other functions that receive arguments
// as reference and value
void arguments() {
int a = 10;
int b = 20;
cout << "\n -------------------\n";
cout << "| Argument passing |\n";
cout << " -------------------\n\n";
cout << "Initial Values:" << endl;
cout << " a = " << a << endl;
cout << " b = " << b << endl;
// Passing arguments by value
swapV(a,b);
cout << "Passing by Value:" << endl;
cout << " a = " << a << endl;
cout << " b = " << b << endl;
// Passing arguments by reference
swapR(a,b);
cout << "Passing by Reference:" << endl;
cout << " a = " << a << endl;
cout << " b = " << b << endl;
}
// This function demostrates the C++ "default"
// argument passing method : by-value
void swapV(int x, int y) {
int tmp = x;
x = y;
y = tmp;
}
// This functions shows how to pass argument
// by-reference in C++
void swapR(int& x, int& y) {
int tmp = x;
x = y;
y = tmp;
}