How to ... in c++ (in examples)

Assembled by Ross Bannister, University of Reading

Reserved Words

asm, auto, bool, break, case, char, class, const, continue, default, delete, do, double,
else, enum, extern, false, float, for, friend, goto, if, inline, int, interrupt,
long, main, naked, new, operator, private, protected, public, register, return,
short, signed, sizeof, static, struct, switch, template, this, true, typedef,
union, unsigned, virtual, void, volatile, while.

Main Body of Code

include statements
Global variable declarations
Type definitions
Enumerator definitions (named integer constants)
Structure definitions
Union definitions
​
Function declarations (not definitions)
​
// Single line comments
/* Multiple
   line
   comments */
​
int main()
{ statements; ...return integer; }
​
Function definitions
​
(integer=0 is normal ending of main)

Data types

Primitive data types

char       (1 byte integer for characters)
int        (2-byte signed integer)
float      (4-byte real)
double     (8-byte real)

Type modifiers

const        (definition of constants)
long         (double length integer)
unsigned     (unsigned integer)
static       (in functions, maintains value between calls)

Casting (type conversion)

int (floatvariable)

Forcing types

9.99f     (forcing to type float)
999L      (forcing to long (4-byte) integer)

Derived data types

Type definitions

typedef variable_type NAME;

Enumerators

enum name
{ integer_identifier1 [= value1],
  integer_identifier2 [= value2],
  ... };

Structures

Union

union name { member_declarations; };

Operators

Arithmetic operators

+, -, *, /     (ordinary arithmetic operators)
%              (remainder)
++, —         (increment, decrement)

Logical operators

&& (and), || (or), ^ (xor), ! (not)

Relational operators

==, !=, <, >, <=, >=

Compound assignment operators

expression1 operator = expression2;
​
is equivalent to:
​
expression1 = expression1 operator expression2;

Control structures

If ... else

if (expression) {statement1;} else {statement2;}
​
The else branch is optional. This is equivalent to:
​
expression1 ? statement1 : statement2

Switch

switch (integer_expression)
{ case integer1:
    statements1;
    break;
  case integer2:
    statements2;
    break;
  default:
    statements3;
}

While

while (logical_expression)
{ statements; }

do ... while

do
{ statements; }
while (logical_expression);

For

for (statement1; expression; statement2)
{ statements; }
​
is equivalent to:
​
statement1;
while (expression)
{ statements;
  statement2; }
​
Common loop usage:
​
for (i=1; i<=100; i++)
{ statements; }

Exiting and skipping loops

break    (exit the loop)
continue (skip to next cycle (statement2 is still evaluated in for loop))

Arrays

Declaration

type array_name [size];
type array_name [sizex][sizey];
type array_name [size] = {value0, value1, ... };
type array_name [sizex][sizey] = {{value00, value01, ... }, {value10, value11, ... }, { ... } };

Using and accessing

array_name [index]
array_name [indexx][indexy]

Pointers

Pointer declaration and null setting

Declaration (with optional setting to the null pointer, two equivalent ways):
type* pointer_name = NULL;
type *pointer_name = NULL;

Pointer creation and deletion

For single variables:
pointer_name = new type;
...
delete pointer_name;
For dynamically allocated (1D) arrays:
pointer_name = new type[size];
...
delete[] pointer_name;
For dynamically allocated 2D arrays - suggested functions (to create and destroy array doubles):
void Array_2d_double_create ( double ***Array,
                              int    ylen,
                              int    xlen )
{ int j;
  *Array = new double *[ylen];
  for (j=0; j<ylen; j++)
  { (*Array)[j] = new double[xlen];
  }
}
...
void Array_2d_double_destroy ( double ***Array,
                               int    ylen)
{ int j;
  for (j=0; j<ylen; j++)
  { delete (*Array)[j];
  }
  delete (*Array);
}
​
To access:
Array[j][i]

Accessing information

To access a pointer’s target:
*pointer_name
If the pointer is to a structure:
(*pointer_name).variable_name
To return a pointer to a variable (useful for call-by-address in function calls):
&variable_name
Allocation check:
(pointer_name)

Characters and Strings

String declaration and setting

Declaration (with optional initialization)
char string_name [] = {char1, char2, ..., \0};
char string_name [] = "literal string";

Special characters

\" double quotes
\’ single quote
\\ backslash
\n newline
\0 null (padding)

String utilities

#include <string.h>
​
// Read a string from a file
fgets (string-pointer, max-length, file-pointer);
​
// Formatted write to a string
sprintf (output-string, "format specifier", inputs, ...);
​
// Size of a string
sizeof (string);
​
​
#include <string.h>
// Extract a sub-string from position n
strncpy (output-substring, original-string + n, length-of-substring);
​
// Copy one string to another
strcpy (output-string, input-string);
​
// Find the place in a string where a substring is located (returns pointer);
sub = strstr (string, substring);
​
// Find the place in a string where a single character is located (returns pointer);
sub = strchr (string, char);
​
// (note the position in the string can be found as pos = sub-string,
//  where pos is an integer, and where 0 corresponds to the first position)
​
// Compare two strings
pos = strcmp (string1, string2);
// Returns 0 when the two strings are equal
​
// Compare two strings (to at most n characters)
pos = strncmp (string1, string2, n);

Input and Output

Keyboard and screen (cout and cin)

#include <iostream.h>
...
cout << exp1 << exp2 ...;
cin >> var1 >> var2 ...;

Keyboard and screen (formatted)

Output to screen:
#include <stdio.h>
...
printf (format_string, exp1, exp2, ...);
Input from keyboard:
scanf (format_string, &exp1, &exp2 , ...);

Format string description

Example used with printf:
printf ("\nThe result for %i is %f", int_var, double_var);
A further example:
printf ("%  8u  %7s  %  8i  %  11.6f\n", int_var1, string_var, int_var2, float_var);
This will:

File IO (formatted)

Open a file:
#include <stdio.h>
...
FILE* file_var = NULL;
...
file_var = fopen (file_name_string, mode_string);
Output to file:
fprintf (file-var, format_string, exp1, exp2, ...);
Input from file:
fscanf (file-var, format_string, &exp1, &exp2 , ...);
Read a whole line as a string:
fgets(string, length-of-string-declaration, file-var);
Closing a file:
fclose (file-var);
Test for end of file:
feof (file-var)

Functions

Declaration

type function_name (arg_type1 arg_name1, arg_type2 arg_name2, ...);

Definition

type function_name (arg_type1 arg_name1, arg_type2 arg_name2, ...)
{ local variable declarations; statements;
  return value;
}

Mathematical operators

#include <math.h>
​
// x to the power of y
pow(x,y);
​
// Absolute value of an integer, i
abs(i);
​
// Absolute value of a double, d
fabs(d);
​
// Copy sign (forms a number with magnitude m and sign s)
copysign (m, s);
​
// pi
const float  pi = 3.14159265359;
​
// Inverse trig functions
asin(ratio);
acos(ratio);
atan(ratio);
atan2(y,x)
​
// Test for not-a-number (nan)
isnan(x);

Inputting information via command line arguments

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
​
int ProgramArguments ( int    arg_count,
                       char   **arg_list,
                       char   *character,
                       char   string[64],
                       int    *integer,
                       double *doublevar );
​
int main ( int   arg_count,
           char  **arg_list )
{ int    success;
  char   character;
  char   string[64];
  int    integer;
  double doublevar;
​
  success = ProgramArguments ( arg_count,
                               arg_list,
                               &character,
                               string,
                               &integer,
                               &doublevar );
​
​
}
​
​
int ProgramArguments ( int    arg_count,    // in  No of args
                       char   **arg_list,   // in  Program arguments
                       char   *character,   // out Example with a character
                       char   string[64],   // out Example with a string
                       int    *integer,     // out Example with an integer
                       double *doublevar )  // out Example with a double
​
{ int success, count;
​
  success      = 1;
  count        = 0;
​
  // Extract the first argument (a character)
  count += 1;
  if (arg_count > count)
  { *character = arg_list[count][0];
    printf ("Argument 1: you entered %c\n", *character);
  }
  else
  { printf ("Argument 1 (a character) expected\n");
    success = 0;
  }
​
  // Extract the second argument (a string)
  count += 1;
  if (arg_count > count)
  { strcpy(string, arg_list[count]);
    printf ("Argument 2: you entered %s\n", string);
  }
  else
  { printf ("Argument 2 (a string) expected\n");
    success = 0;
  }
​
  // Extract the third argument (an integer)
  count += 1;
  if (arg_count > count)
  { *integer = atoi(arg_list[count]);
    printf ("Argument 3: you entered %i\n", *integer);
  }
  else
  { printf ("Argument 3 (an integer) expected\n");
    success = 0;
  }
​
  // Extract the fourth argument (an double precision)
  count += 1;
  if (arg_count > count)
  { *doublevar = atof(arg_list[count]);
    printf ("Argument 4: you entered %f\n", *doublevar);
  }
  else
  { printf ("Argument 4 (a double) expected\n");
    success = 0;
  }
​
  return success;
}
​

Miscellaneous

Exit code

#include <stdlib.h>
​
exit(status);

Check potential problems with source code (linux command)

cppcheck source_code.cpp --enable=all

Numerical libraries

FFTw

// Include
#include <fftw3.h>
​
// Compilation and linking
// g++ code.cpp -o code.out -lfftw3 -lm
​
// Data types
fftw_complex  //(this is a double[2], element [0] is real part, element [1] is imaginary part)
fftw_plan     // (this specifies the input/output arrays and the transform type)
​
// Example FT and inverse
fftw_complex realspace[100], spectralspace[100], realspace1[100];
fftw_plan    plan;
​
plan = fftw_plan_dft_1d(100, realspace, spectralspace, FFTW_FORWARD, FFTW_ESTIMATE);
fftw_execute(plan);
​
plan = fftw_plan_dft_1d(100, spectralspace, realspace, FFTW_BACKWARD, FFTW_ESTIMATE);
fftw_execute(plan);

Gnu Scientific Library

// Include (the appropriate routine is found in /usr/local/include/gsl)
#include <gsl/...h>
// Compilation and linking
// g++ code.cpp -o code.out -lgsl -lgslcblas -lm