Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
38 views

SOFT336 Cross-Platform Application in C++

This document provides a summary of C++ syntax including data types, variables, constants, operators, control flow statements like if/else and loops, functions, arrays and comments. Key areas covered are case sensitivity, identifier naming conventions, comment formats, variable declaration and initialization, operator precedence, and passing arguments by value or reference in functions. The document is intended as a handy reference for C++ coding.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

SOFT336 Cross-Platform Application in C++

This document provides a summary of C++ syntax including data types, variables, constants, operators, control flow statements like if/else and loops, functions, arrays and comments. Key areas covered are case sensitivity, identifier naming conventions, comment formats, variable declaration and initialization, operator precedence, and passing arguments by value or reference in functions. The document is intended as a handy reference for C++ coding.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

SOFT336 Cross-platform application in C++

C++ Syntax Guide


This handout summarises the syntax of the C++ language. You should read through it carefully, and keep it
handy whenever you are doing any coding.

The areas covered are as follows:


General information .............................................................................................. 2
case ............................................................................................................... 2
identifiers ..................................................................................................... 2
conventions .................................................................................................. 2
coding style .................................................................................................. 2
comments ..................................................................................................... 3
data types ..................................................................................................... 3
casting .......................................................................................................... 3
variables ....................................................................................................... 4
constants ...................................................................................................... 4
assignment ................................................................................................... 4
operators ...................................................................................................... 4
Iteration statements (loops) .................................................................................. 6
deterministic loop (for) ................................................................................ 6
pre-conditioned non-deterministic loop (while) ......................................... 6
post-conditioned non-deterministic loop (do ~ while) ................................ 6
Selection statements (if and case structures) ....................................................... 8
if statements ................................................................................................ 8
if ~ else if ~ ................................................................................................... 8
switch statement .......................................................................................... 9
Programmer-defined subprograms ..................................................................... 11
returning values ......................................................................................... 11
Pascal-type procedures .............................................................................. 11
Pascal-type functions ................................................................................. 12
good practice .............................................................................................. 12
passing by value or by reference ............................................................... 12
Arrays ................................................................................................................... 13
general ........................................................................................................ 13
declaration ................................................................................................. 13
initialisation ................................................................................................ 13

C++ Syntax Guide Page 1


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?

text=studentName;if (totalMark>=40) {text=text+"has passed";grade


=1;} else {text=text+"has failed";grade=0;}
or
text=studentName;
if (totalMark>=40)
{
text=text+"has passed";
grade=1;
}
else
{
text=text+"has failed";
grade=0;
}
Compressing code doesn't save space!

Comments
There are two ways of denoting comments:

C++ Syntax Guide Page 2


SOFT336 Cross-platform application in C++
 introduce with /* and terminate with */ (this allows multi-line comments)
e.g.
/* This method allows a new object to be constructed without
parameters, using defaults for the initial values. */

 // makes the remainder of the line a comment


e.g.
int lines; // line count

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:

// Loop through the array, calculating


// the sum of the values, then calculate the
// average.

for (int i = 0; i < noOfValues; i++)


sum = sum + value[i];

average = sum / noOfValues;

Data types
Type Description
Int Integers
float floating point
double double precision floating point
bool Boolean
char single character

 note that C++ doesn’t have a fundamental string type.

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;

C++ Syntax Guide Page 3


SOFT336 Cross-platform application in C++
Constants
Literal constants - for strings and characters, it is important to use the correct punctuation.
 For a character constant use single quotes, e.g. 'a'
 For a string constant use double quotes, e.g. "Hello world"

Symbolic constants – as created using the const keyword


const int MAXRECORDS = 100;

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;

The full range of assignment operators is:


+= addition
-= subtraction
*= multiplication
/= division
%= modulus

Logical operators:

C++ Syntax Guide Page 4


SOFT336 Cross-platform application in C++
The main differences here are the equals and not equals operators. Because the = symbol is used to assign a
value to a variable, a different operator is used to test equality: the == operator. Inequality is tested using !=
< less than
<= less than or equal
> greater than
>= greater than or equal
== equal
!= not equal

&& 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!

C++ Syntax Guide Page 5


SOFT336 Cross-platform application in C++

Iteration statements (Loops)


The deterministic loop: for
A deterministic loop (i.e. one that provides some incrementing of a counter) is provided by the for statement:

for (initialisation; condition; increment)


statement;

initialisation is an expression setting an initial value


condition: looping continues while this expression is true
increment is an expression that increments the counter

Note that the brackets around the control part are mandatory.

for (count = 0; count < 10;


count = count + 1)
{
…statement(s) …
}

The pre-conditioned non-deterministic loop: while


A pre-conditioned loop (where the testing of the terminating condition occurs before execution of the loop
statements) is provided by the while statement:

while (condition)
statement;

repeats the statement (or block) while the condition is true.

Note that the brackets around the condition are mandatory.

Example:
count = 0;
while (count <= 10)
{
sum += values[count];
count ++;
}

The post-conditioned non-deterministic loop: do … while …


A post-conditioned loop (where the testing of the terminating condition occurs after execution of the loop
statements) is provided by the do … while statement:

do statement
while (condition);

repeats the statement (or block) while the condition is true.

Note that the brackets around the condition are mandatory.

The loop is always executed at least once.

Example (overleaf):

C++ Syntax Guide Page 6


SOFT336 Cross-platform application in C++
count = 0;
do
{
sum += values[count];
count ++;
} while (count <= 10)

C++ Syntax Guide Page 7


SOFT336 Cross-platform application in C++
Selection statements (if and case)
The if statement
if allows a choice of two different paths to be taken depending on whether a logical expression is true or false.

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;

This can be more efficient than several if statements.

Example:
if (mark < 40)
result = "Fail";
else if (mark < 50)
result = "Lower second";
else if (mark < 60)
result = "Upper second";
else
result = "First";

The switch statement


switch allows multiple paths to be selected depending on the value of a variable, i.e. a case type of structure.

Syntax:

C++ Syntax Guide Page 8


SOFT336 Cross-platform application in C++
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
...
default:
statementd;
}

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;
}

C++ Syntax Guide Page 9


SOFT336 Cross-platform application in C++

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!

C++ Syntax Guide Page 10


SOFT336 Cross-platform application in C++

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

type function-name(type p1, ...)

return the name of parameter parameter


type the function type name

a type name, or usually starts variable name,


void if there is with a lower starts with a
nothing returned case letter lower case letter

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.

Consider this Pascal procedure:


procedure ShowResult(NumVal:real);
begin

C++ Syntax Guide Page 11


SOFT336 Cross-platform application in C++
EdtTotal.Text := FloatToStr(NumVal);
end;

The equivalent in Java would be:


void showResult(float numVal)
{
edtTotal.Text = ' ' + numVal;
}

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.

Consider this Pascal function:


function Square(Num: integer): integer;
begin
Square := Num * Num; (or result := Num * Num;)
end;

In C++, the equivalent would be:


int Square(int num)
{
return (num * num);
}

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.

Passing by value or by reference


The parameters in the above examples are all being passed by value. If you want to pass a parameter by
reference instead, you add an & to its type in the function header. For example, if you wrote a function to find
the minimum and maximum of a range of values, you could return these via parameters using the following:

findMinAndMax(int* arrayOfValues, int noOfValues, int& minValue,


int& maxValue)
{
: : :
}

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.

C++ Syntax Guide Page 12


SOFT336 Cross-platform application in C++

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 ];

For example, to declare an array of 10 integers:


int nums[10];
Arrays are indexed from zero, so the subscripts for the nums array would range from 0 to 9.

Multi-dimensional arrays can be used, e.g.


int frequency[2][4];
In effect, this declares two arrays of arrays of four integers.

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).

A declaration such as:


int nums[ ]={0,1,2,3,4,5,6,7,8,9};
would make the array 10 elements long.

To initialise a multi-dimensional array:


int freq[2][4]={ {0,0,0,0},{0,0,0,0} }

C++ Syntax Guide Page 13

You might also like