SOFT336 Cross-Platform Application in C++
SOFT336 Cross-Platform Application in C++
General Information
C++ is case-sensitive!
This means that a variable named as Count, for example, would NOT be the same as a variable named as
count or COUNT. So, if you get an error message telling you that an identifier has not been declared, and you
think you have declared it, check the case!
Identifiers
These are the words that define statements, variable names, function names, and so on. The rules for making
up identifiers are:
you may use only letters, digits and underscore
they must start with a letter or underscore (but avoid starting with underscore as this may be used for
system functions and constants)
any length, but only first 32 characters significant??
certain identifiers are reserved as keywords
Conventions
variable names - mostly in lower case, using camelCaps, i.e. start with lower case, and if multiple words
are used, start each subsequent word with a capital, e.g. grandTotal, numberOfLines. Underscores are not
commonly used in variable names. You should not need to be reminded to use meaningful names!
function names – same as for variable names, e.g. changeStatus , getTotal.
class names – same as for variable names but with the first letter as a capital, e.g. Person, Car, User.
keywords (i.e. those that represent statements, like if and while, and data types) – always in lower case –
you have no choice. If you use the wrong case for a keyword it will not be recognised!
Coding style
Statements are terminated by ; characters.
Blocks start with { and end with } .
A statement can be split over several lines – you can help make the code clearer and avoid untidy word
wrap!
Blank lines between statements can improve clarity.
Use indenting within structures for clarity – which do you prefer?
Comments
There are two ways of denoting comments:
Using comments:
Introduce every program with a comment - giving name, date written, outline of purpose.
Add comments to your code as you write it (so that later on you will remember why you did it that way!).
Don’t undercomment and don’t overcomment. It is better to put two or three lines at the start of several
lines of code, giving a general description, rather than add comments to the ends of lines which can make
code difficult to read and difficult to modify!
For example:
Data types
Type Description
Int Integers
float floating point
double double precision floating point
bool Boolean
char single character
Casting
Used to carry out temporary conversion of a value to another type, for example converting an integer type to a
floating point type in order to avoid integer division. To cast the value of an expression to another type,
precede the expression with the required type name, enclosed in round brackets, e.g.
average = sum / (float)noOfValues;
Variables
Declaration: To declare a variable, give the type, then one or more spaces, then the name, then a semicolon.
int total;
float sum;
Initialisation: Variables are not automatically initialised to zero, but you can specify an initial value when
declaring the variable, e.g.
int value = 0;
Assignment
To assign a value to a variable:
variable = expression;
e.g.
a = b + 2;
Operators
Basic arithmetic operators are:
+ addition
- subtraction
* multiplication
/ division
% modulus (i.e.remainder)
Usual precedence is applied, i.e. * and /, then + and -. Use brackets if needed to change precedence.
Increment/decrement operators increment or decrement a variable and place the result back in the variable.
Symbols used are ++ and --
e.g. x ++; in C++ is equivalent to x = x + 1;
Precedence can be important here if you assign the result to another variable as well. For example if the
variable x has the value 10 and you use a statement such as:
y = x ++;
The result of this would be to place the initial value of x (i.e. 10) in the variable y, then to increment x, so that y
would be 10 and x would be 11.
If you used a statement such as
y = ++ x;
the result would be to increment x by 1 and then copy the value into y, so both x and y would be 11.
The same goes for the -- operator.
Assignment operators carry out an operation and assign the result using one operator. They carry out an
operation using the operands on either side of the operator, and assign its result to the operand on the left
hand side of the operator.
For example:
invoiceTotal += itemTotal;
is another way of writing:
invoiceTotal = invoiceTotal + itemTotal;
Logical operators:
&& AND
|| OR (inclusive)
! NOT
Logical expressions:
Any expression that evaluates to zero is false.
Any expression that evaluates to a non-zero is true.
For example:
if (choice != 0)
statement;
could be abbreviated to:
if (choice)
statement;
but don't sacrifice clarity for the sake of three extra characters!
Ensure that you use the correct operator for equality: if (a = 0) is syntactically correct, but will have the
opposite effect from that required, since the expression evaluates to 0 and is therefore false!
Note that the brackets around the control part are mandatory.
while (condition)
statement;
Example:
count = 0;
while (count <= 10)
{
sum += values[count];
count ++;
}
do statement
while (condition);
Example (overleaf):
if (expression)
statement1;
else
statement2;
Note:
else... can be omitted if no action is required when the condition is false.
statement1 and statement2 can be replaced by a block of statements enclosed in { }.
The brackets around the condition are mandatory.
As with any language, indenting is important for clarity.
Example:
if (count == 0)
average = 0;
else
average = sum / count;
if … else if …
Where there are more than two choices, if...else if … can be used:
if (expression1)
statement1;
else if (expression2)
statement2;
else if (expression3)
statement3;
...
...
else
statementn;
Example:
if (mark < 40)
result = "Fail";
else if (mark < 50)
result = "Lower second";
else if (mark < 60)
result = "Upper second";
else
result = "First";
Syntax:
expression is evaluated, and its value used to determine which case is to be executed.
default indicates what to do if none of the cases was actioned.
break is needed to exit from a case. If omitted, the chosen case will be executed, followed by all subsequent
cases unconditionally!
Examples:
switch (operationType)
{
case '+':
addValues(v1, v2);
break;
case '-':
subtractValues(v1, v2);
break;
case '*':
multiplyValues(v1, v2);
break;
case '/':
divideValues(v1, v2);
break;
}
switch (monthNo)
{
case 2:
noOfDays = 28;
break;
case 4:
case 6:
case 9:
case 11:
noOfDays = 30;
break;
default:
noOfDays = 31;
break;
}
Note: it is good practice to follow the last case with a break, even though it is not required – if more cases are
added later, you might forget to add the break and get a logic error!
Programmer-defined subprograms
Unlike Pascal, C++ has only one type of sub-program (the function). However, the two styles of sub-program
(procedure and function) are still available.
Function headers give the type of expression returned (if any), the name of the function, and types and names
of any parameters.
Syntax:
brackets are
empty if there are
no parameters
Returning values
Use the return statement to return a single value from a function. Alternatively, parameters can be used
(covered later).
Example:
int Square(int numValue)
{
return numValue * numValue;
}
Functions that do not return a value are declared as void, and therefore either have no return statement at all,
or have a return statement with no value, i.e.
return;
On the next page, you will see an example of a Pascal procedure and a Pascal function, and the way the two
would be written in Java.
Pascal-type procedures
A Pascal procedure does not return a value, so the equivalent in C++ would be a function with void as the
return type.
Pascal-type functions
A Pascal function does return a value, so the equivalent in Java would be a function with the type of value
returned as its return type.
Good practice
Include comments before the function giving information on its purpose, its parameters, and information
it returns.
The default return type is int, and empty brackets imply the default of void (no parameters). However, it is
good practice to include the word void and to always specify the return type.
The last two parameters are passed by reference. Note that when the function was called, you would just state
the variable names as usual.
The first parameter is another example of passing by reference - the * indicates that the item passed to the
function will be a pointer to an int variable. When passing an array as a parameter, you pass the address of
the first element of the array. Again, when calling the function, you would just put the array name.
There are a few more twists to the use of pointers and references, but I will deal with them as and when we
need to - if necessary you can consult text books.
Arrays
General
Hold a collection of variables of the same type.
Instead of individual names, they use the array name followed by a subscript in square brackets, e.g.
range[i]
Subscripts go from 0 to (length – 1)
So, an array of 10 items has its elements numbered 0 to 9
Declaration
To declare an array:
type name[ size ];
Initialisation
Arrays can be initialised on declaration, e.g.
int nums[10] = {2,3,2,1,1,4,4,3,5,6};
Giving fewer values than there are elements would initialise the first elements, e.g.
int nums[10] = {0,1,2};
would initialise the first three elements and leave the rest undefined (or set to zero for a global array).