· Now build (F7) and execute your code.
Variables, datatypes and functions
Variables are named memory locations of a size determined by the declared datatype.
The following table lists some of the simple datatypes available in C++.
Datatype Description and Range
bool One of two values only. e.g. True or False
unsigned char Positive numeric values without decimals from 0-255
unsigned short
(OR int)
Integers from 0 – 65,535 (but the older int is system
dependent).
short int Integers from –32,768 to 32,767
unsigned long int Integer values from 0 to 4,294,967,295
long int Integer values from –2,147,483,648 to 2,147,483,647
float Real numbers to 3.4E +/- 38 (7 digits)
double Real numbers to 1.7E +/- 308 (15 digits)
(You can also have a long double
at 1.2E +/- 4932 (19 digits)
CString Not really a simple datatype. A predefined C++ class for
handling strings of alphanumeric characters
enum For defining datatypes based on predefined datatypes
A function is a segment of code that accepts zero, one or more arguments and returns a
single result. Some perform basic mathematical tasks, e.g.
//NB This code depends on using the #include <CMath> header file
// at the beginning of this code.
unsigned long myValue = 2;
unsigned long cubed = cube(myValue)
unsigned long squared = square(cubed)
//cubed = 8
//squared = 64
Classes combine data and related functions (called methods of the class).
An argument is a value you pass to a function so the function has data to work with.
myValue and cubed are both examples of arguments.
A function is declared in a function prototype using the following syntax:
return_type function_name ([type[parameterName]] …);
For example, int CalculateArea(int length, int width);
A function prototype tells the compiler the return type, name and parameter list. Functions
are not required to have parameters but must contain the parentheses even if empty. A
function may take the return type void if no value is to be returned. A prototype always
ends with a semicolon.
The function definition tells the compiler how the function works using this syntax:
return_type function_name ([type parameterName]…)
{
statements;
}
For example,
int CalculateArea(int l, int w)
{
return l*w;
}
A function definition must agree with its prototype in return type and parameter list. It
must provide names for all the parameters, and braces must surround the body of the
function. All statements within the braces must end in semicolons, but the function itself is
not ended with a semicolon.
No comments:
Post a Comment