To run a C++ program:
myprogram.cpp
)cd
command to get to the folder where your C++ files areg++ myprogram.cpp
to compile. If there are error messages, correct the mistake and compile again (note: an old executable a.out
will still be there until it is overwritten by a new one. If your program failed to compile and you still try to run it, you would be running the old version).a.out
on the command line. If you get file not found
error, use ./a.out
instead.The example illustrates parameter passing in (old style) C++
#include <iostream> // need this header file to support the C++ I/O system
using namespace std; // using the standard namespace "std",
// function declarations - needed for the program to compile
void by_value(int n);
void by_reference(int *p);
void swap(int *p, int *q);
int main()
{
int n = 2, m = 1;
int *p = &n;
int *q = &m;
// passing an integer by value
by_value(n);
cout << n << endl;
by_value(*p); // cannot pass just p
cout << n << endl;
by_reference(&n); // cannot pass just n
cout << n << endl;
by_reference(p);
cout << n << endl;
// swaping n and m
swap(&n, &m);
cout << "n = " << n << " m = " << m << endl;
swap(p, q);
cout << "n = " << n << " m = " << m << endl;
return 0;
}
void by_value(int k) {
k = k + 1;
}
void by_reference(int *r) {
*r = *r + 1;
}
void swap(int *first, int *second) {
int temp = *first;
*first = *second;
*second = temp;
}