#include <iostream.h> const int SIZE = 20; typedef float floatarray[SIZE]; void printarray(floatarray arr); void main() { floatarray myarray; for (int index = 0; index < SIZE; index++) { myarray[index] = index * 1.5; } printarray(myarray); } void printarray(floatarray arr) { for (int index = 0; index < SIZE; index++) { cout << arr[index] << endl; } }
float myfloat = 3.7; int myint = 29; char mychar = '?'; mychar = char(myint); myint = int(myfloat);float to int conversion is done by rounding down (truncating)
char to int conversion (and int to char) is done using the ascii tables for matching character values to integers
const int DaysInYear = 365; const float Pi = 3.14; const char Blank = ' ';
static
retain their values
across function calls
extern
in all files except X int myint, anotherint, andanotherint; float fees = 0.0; static char initial = 'D'; extern Boolean quit;
int sumandtruncatefloats(float f, float g) { return( int(f+g) ); }
The corresponding function declarations and calls might be
int sumandtruncatefloats(float f, float g); ... float y = 2.914; int x; x = truncatefloat(3.7 + y);
Pass-by-reference, or reference parameters, allow the function to alter the value of a variable passed to it
void validswap(int &x, int &y) { int temp; temp = x; x = y; y = temp; }The call
validswap(var1, var2);
would swap the values of
variables var1 and var2.
Arrays and structs are automatically passed by reference - to prevent this prefix them with const in the parameter list:
void foo(const char str[], int length); ... foo(mystring, SIZE);
void validswap(int *x, int *y) { int temp; temp = *x; *x = *y; *y = temp; } ... validswap(&var1, &var2)
int X = 0; float y = 3.7; char c = 'a'; char myarray[4] = "xyz\0"; cout << "X has value " << X << endl << "y has value " << y << endl; cout << "c has value " << c << endl << "myarray has value " << myarray << endl;
cout << setw(3) << x;
cout << setiosflags(ios::fixed) << setprecision(N) << x;
int X; float y; char c; char myarray[4]; cin >> X >> y >> c >> myarray;
cin.get(c); // where c is a char variable
cin.getline(mystring, Size-1); // where mystring is an array of Size chars
long bignum; int hexnum; char c, word[20]; scanf("%ld %s %x", &bignum, &word, &hexnum); printf("long: %ld, hex: %x, word: %s \n", bignum, hex, word); c = getchar(); /* equiv. to c = getc(stdin); */ putchar(c); /* equiv. to putc(c, stdout); */Available formats:
// C++ version #include <iostream.h> #include <fstream.h> ofstream outfile; ifstream infile; void main() { char infilename[SIZE]; char outfilename[SIZE]; char wholeline[SIZE]; char c; cin >> infilename; cin >> outfilename; infile.open(infilename); if (infile.fail()) exit(1); outfile.open(outfilename); if (outfile.fail()) exit(2); infile.getline(wholeline, SIZE); while (!infile.eof()) { infile >> nextword; infile.get(c); outfile << nextword; outfile << c; } infile.close(); outfile.close(); }
#include <stdio.h> #include <file.h> FILE *infile, *outfile, *fopen(); void main() { char infilename[SIZE], outfilename[SIZE]; char c, wholeline[SIZE]; infile = fopen("filename1", "r"); outfile = fopen("filename2", "w"); if (infile == NULL) exit(1); while (!feof(infile)) { fgets(wholeline, SIZE, infile); c = getc(infile); putc(outfile); } fclose(infile); fclose(outfile); }
#include <stdlib.h> void main(int argc, char *argv[]) { cout << "You called program " << argv[0] << " with arguments " << endl; for (int i = 1; i < argc; i++) { cout << argv[i] << " "; } cout << endl; }Making unix system calls
char commandline[256]; cin >> filename; strcpy(commandline, "cat "); strcat(commandline, filename); strcat(commandline, " | wc >> "); strcat(commandline, filename); strcat(commandline, ".out"); system(commandline);
if (<Boolean expression) { // statements if expression is true } else { // statements if expression is false }The "else" portion of the statement is optional.
if (x == 3) { // statements for x == 3 } else if (x == 7) { // statements for x == 7 } else if (x < 0) { // statements for x is negative } else { // statements for all other values of x }
switch (x) { case 3: // statements for x == 3 break; case 7: // statements for x == 7 break; default: if (x < 0) { // statements for x is negative } else { // statements for all other values } }Leaving out the break statements can allow us to group values for which we want similar behaviour, e.g.:
switch (c) { case 'q': case 'Q': // statements for letter q break; case 'c': case 'C': // statements for letter c break; default: // statements for all other letters }
for (<initialisation>; <continuance test>; <update> ) { <executable statements> }Example: consider all even integers from 0 through 98
for (int x = 0; x < 100; x += 2) { // statements to be executed }
while (<Boolean expression) { // statements to be executed }Meaning: as long as the Boolean expression evaluates to true, carry out the body of the loop.
Example: repeat until the user enters Q
char c = 'C'; while (c != 'Q') { // executable statements cout << "Enter Q to quit, C to continue" << endl; cin >> c; }
do { // statements to be executed } while (<Boolean expression>);
Example: repeat until the user enters a positive value:
do { cout << "Enter a postive integer" << endl; cin >> x; } while (x <= 0);
// declare a type of array to hold 50 floats const int Size = 50; typedef float floatarray[Size]; // declare an actual array variable floatarray myfloats;
arrayname[i]
, e.g.: myfloats[3] = 17.4; myfloats[2] = myfloats[3] + 4.1; x = sqrt(myfloats[2]);
myarray[i]
is functionally identical to
*(myarray + i)
void fillarray(floatarray arr, int arrsize); void main() { floatarray myfloats; fillarray(myfloats, Size); } void fillarray(floatarray arr, int arrsize) { cout << "Enter " << arrsize << " floats" << endl; for (int i = 0; i < arrsize; i++) { cin >> arr[i]; } }To pass arrays as value parameters prefix them with
const
in the parameter list, e.g. void viewarray(const floatarr arr, int
arrsize);
They are stored in row-major order
const int Rows = 10; const int Columns = 16; typdef char grid[Rows][Columns]; void main() { grid Mygrid; for (int r = 0; r < Rows; r++) { for (int c = 0; c < Columns; c++) { Mygrid[r][c] = ' '; } } }To pass multidimensional arrays as parameters you must declare (in the parameter list) the size of all dimensions except the first, e.g.:
int matrix[20][30]; void initmatrix(int m[][30], int rows);
typedef struct { <type> field1; <type> field2; ... <type> fieldN; } <typename>;The syntax for accessing a field value is
<varname>.<fieldname>
Example: employee record
typedef struct { string surname; string givenname; float hourlywage; } EmployeeRec; void main() { EmployeeRec employee1; strcpy(employee1.surname, "Wessels"); strcpy(employee1.givenname, "Dave"); employee1.hourlywage = 0.01; }
typedef struct { string bossname; int numemployees; EmployeeRec staff[Size]; } StaffList; void main() { StaffList Meagresoft; strcpy(Meagresoft.bossname, "Gill,Bates"); int numemployees = Zillion; for (int slave = 0; slave < Size; slave++) { strcpy(Meagresoft.staff[slave].surname, " "); strcpy(Meagresoft.staff[slave].givenname, " "); Meagresoft.staff[slave].hourlywage = 35.0; } }
void initcomp(StaffList company); void main() { StaffList Meagresoft; initcomp(Meagresoft); ... }
enum booleflag { false, true }; booleflag = true;
#include <iostream.h> #include <stdlib.h> #include <time.h> // C++ random number generator for values between X and Y void main() { int X, Y, result; srand((unsigned int)(time(NULL))); cin >> X >> Y; result = (rand() % (top + 1 - bottom)) + bottom; cout << result << endl; }
#include <iostream.h> #include <math.h> // compile using g++ progname.cpp -o progname -fhandle-exceptions -lm void main() { float x, y; cout << "Enter a numerator and denominator" << endl; cin >> y >> x; // a try block contains exception handling // exceptions are invoked with throw() try { if (x == 0) throw("Divide by zero\0"); if ((y/x) < 0) throw("Sqrt of negative\0"); cout << "sqrt(" << y << "/" << x; cout << ") is " << sqrt(y / x) << endl; } // exceptions are handled with catch() catch(char str[]) { cout << str << endl; throw; // re-throws any unhandled errors } }
int x; // x is an integer int *x_ptr; // x_ptr is a pointer to an integer x_ptr = &x; // make x_ptr point to x x = 3; cout << x << " " << *x_ptr; // print out 3 3Pointers to functions:
int foo(float x); int (*f_ptr) (); // f_ptr can point to any function // which returns an int f_ptr = foo; // f_ptr points to function foo y = (*f_ptr)(3.7); // equivalent to y = foo(3.7);
// want an array of 10 student records StudentRec *s_ptr; s_ptr = (StudentRec *)calloc(10, sizeof(StudentRec)); // or alternatively // s_ptr = (StudentRec *)malloc(10 * sizeof(StudentRec));
myglobal
is declared in first.cpp
and used in main.cpp
make
mainprog
, and the system will automatically compile exactly those
files which have been altered since the last time make was run Dependencies: mainprog / | \ / | \ first.h | second.h \ | / \ | / boolean.h //-------------------------------------------------------------------- // File boolean.h: gets included from several .h files // and the main program //-------------------------------------------------------------------- #ifndef BOOLE #undef TRUE #undef FALSE typedef int Boolean; const int TRUE = 1; const int FALSE = 0; #define BOOLE #endif //-------------------------------------------------------------------- // File first.h: gets included from main, // is header for first.cpp routines //-------------------------------------------------------------------- #ifndef FIRST #include "boolean.h" int foo(char c); #define FIRST #endif //-------------------------------------------------------------------- // File first.cpp: body of routines from first.h //-------------------------------------------------------------------- #include#include "first.h" int myglobal; int foo(char c) { cout << "C is " << c << endl; return( int(c) ); } //-------------------------------------------------------------------- // File second.h: gets included from main, // is header for second.cpp routines //-------------------------------------------------------------------- #ifndef SECOND #include "boolean.h" char blah(int x); #define SECOND #endif //-------------------------------------------------------------------- // File second.cpp: body of routines from second.h //-------------------------------------------------------------------- #include #include "second.h" char blah(int x) { cout << "X is " << x << endl; return( char(x) ); } //-------------------------------------------------------------------- // File mainprog.cpp: main program, uses seperately compiled files // first.o and second.o //-------------------------------------------------------------------- #include #include "first.h" #include "second.h" #include "boolean.h" extern int myglobal; void main() { int mynum; char mychar; mynum = foo('Z'); mychar = blah(mynum); } //-------------------------------------------------------------------- // File makefile: make mainprog - brings mainprog up to date, // updates other files only if needed // make clean - gets rid of .o files //-------------------------------------------------------------------- mainprog: first.o second.o mainprog.cpp g++ first.o second.o mainprog.cpp -o mainprog first.o: first.cpp g++ -c first.cpp second.o: second.cpp g++ -c second.cpp clean: rm -f *.o
class Myclass { public: // constructor Myclass(); // destructor ~Myclass(); // inline functions int returndata() { return(mydata); } void setdata(int x) { mydata = x; } // general functions void dosomework(); private: // private functions void adjustdata() { mydata++; } // private data int mydata; Myclass *classptr; } Myclass::Myclass() { mydata = 0; } Myclass::~Myclass() { delete classptr; } void Myclass::dosomework() { classptr = new Myclass; classptr->setdata(mydata + 1); } void main() { Myclass classvar; classvar->dosomework(); }
/* * compile using cc -threads filename.c -o filename */ #include#include #include #define TRUE 1 #define FALSE 0 // macro for checking results of thread creation #define CHECK(status, string) if (status == -1) perror(string) // threads to be created pthread_t firstthread, secondthread; // trigger to allow start of thread routines int go = 0; void ThreadRoutine(pthread_addr_t arg) { // get thread identifier long int mynum; mynum = (long int) arg; // wait for release while ((!go)) {}; // body of thread routine printf("Running thread routine %ld \n", mynum); system("ps -jlm"); // terminate routine pthread_exit(arg); } void main() { int status; // set thread identifier long int threadNum = 0; // value of exit from join call pthread_addr_t exit_value; // create the first thread and make sure its status is ok status = pthread_create( &firstthread, pthread_attr_default, (pthread_startroutine_t)ThreadRoutine, (pthread_addr_t) threadNum); CHECK(status, " :pthread_create bad status\n"); // create the second thread and make sure its status is ok threadNum = 1; status = pthread_create( &secondthread, pthread_attr_default, (pthread_startroutine_t)ThreadRoutine, (pthread_addr_t) threadNum); CHECK(status, " :pthread_create bad status\n"); // release the thread printf("Releasing the threads\n"); go = 1; printf("Threads released\n"); printf("Joining threads\n"); status = pthread_join( firstthread, &exit_value); status = pthread_join( secondthread, &exit_value); printf("Detaching threads\n"); status = pthread_detach( &firstthread ); status = pthread_detach( &secondthread ); printf("Threads terminated\n"); }
/* * compile using cc -threads filename.c -o filename */ #include#include #include #define TRUE 1 #define FALSE 0 // number of threads to be created #define Maxthreads 10 // macro for checking results of thread creation #define CHECK(status, string) if (status == -1) perror(string) // threads to be created pthread_t threads[10]; // mutual exclusion semaphore to be used pthread_mutex_t MutexSem; // trigger to allow start of thread routines int go = 0; void ThreadRoutine(pthread_addr_t arg) { // get thread identifier long int mynum; mynum = (long int) arg; // wait for release while ((!go)) { }; // body of thread routine // critical section pthread_mutex_lock(&MutexSem); printf("Running thread routine %ld in critical section\n", mynum); pthread_mutex_unlock(&MutexSem); // terminate routine pthread_exit(arg); } void main() { // return value from thread/semaphore function calls int status; // thread identifier long int threadNum; // value of exit from join call pthread_addr_t exit_value; // initialise the semaphore status = pthread_mutex_init (&MutexSem, pthread_mutexattr_default); CHECK (status, " :Mutex_init bad status \n"); // create the threads and make sure their status is ok for (threadNum = 0; threadNum < Maxthreads; threadNum++) { status = pthread_create( &threads[threadNum], pthread_attr_default, (pthread_startroutine_t)ThreadRoutine, (pthread_addr_t) threadNum); CHECK(status, " :pthread_create bad status\n"); } // release the thread printf("Releasing the threads\n"); go = 1; printf("Threads released\n"); printf("Joining threads\n"); for (threadNum = 0; threadNum < Maxthreads; threadNum++) status = pthread_join( threads[threadNum], &exit_value); printf("Detaching threads\n"); for (threadNum = 0; threadNum < Maxthreads; threadNum++) status = pthread_detach( &threads[threadNum] ); printf("Threads terminated\n"); }