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 C++ type system (or a lack of one?)
#include <iostream> // need this to use the I/O system
using namespace std; // telling the compiler to use namespace "std",
// where the C++ library is declared.
int main()
{
int n = 5, m = 3;
int *p = &n; // p is a pointer to int, points to n
int *q = &m; // q is a pointer to int, points to m
*p = 6; // changing n via p
cout << "n = " << n << endl; // printing n
q = p; // copied the address from p to q
cout << "*q = " << *q << endl; // printing what q points to
m = 6;
q = &m;
cout << "Below 1 represents true, 0 represents false " << endl;
cout << "m == n: " << (m == n) << endl;
cout << "*p == *q: " << (*p == *q) << endl;
cout << "p == q: " << (p == q) << endl;
// Booleans are not a separate type in C++,
// they are integers: 0 = false, any other value means true
// Boolean operations are applicable to integers (and chars)
cout << "true = " << true << endl;
cout << "false = " << false << endl;
if (2) cout << "2 means true" << endl;
if (!0) cout << "0 means false" << endl;
if ('A') cout << "characters with non-zero ASCII code are true, too" << endl;
if (! '\0') cout << "end of string character '\\0' means false" << endl;
cout << (('?' - 6) || !89) << " = ('?' - 6) || !89 - Huh? That's an integer, too?" << endl;
const int size = 3;
int A[size];
// array elements are not initialized
cout << "Printing uninitialized array..." << endl;
for (int i = 0; i < size; ++i) {
cout << A[i] << endl;
}
// going through the array using pointers
for (p = A; p < A + size; p++) {
*p = 0;
}
cout << "Printing the array initialized to 0s..." << endl;
for (int i = 0; i < size; i++) {
cout << A[i] << endl;
}
// All of these are the same:
cout << "A[2] = " << A[2] << endl;
cout << "*(A + 2) = " << *(A + 2) << endl;
cout << "2[A] = " << 2[A] << endl;
return 0;
}