Programming in C++

C++ Basics

C++ syntax

The syntax of C++ is extremely critical. By definition, syntax is the rules governing the formation of statements in a programming language. In other words, it is the specific language (code) you use to turn algorithms into programs and specifc rules you have to follow when programming with C++. As you will find out, if you make one small mistake when writing code, the compiler will notify you of the syntax error when you try to run it. C++, like all languages, is very picky when it comes to syntax. Let's look at a simple example program written in C++.

// BEGIN PROGRAM [using Dev-C++ Compiler]
// Program to calculate the average of 3 integers
// Programmer: Mike Ware
// Last Updated: 9/5/02

#include <iostream.h>    // header file for input/output stream
#include <stdlib.h>    // header file for standard input/output

int main( )
{
    int number1, number2, number3;    // declaration of variables
    float average;

    cout << endl << endl;
    cout << "Enter first integer: ";
    cin >> number1;
    cout << "Enter second integer: ";
    cin >> number2;
    cout << "Enter third integer: ";
    cin >> number3;

    average = (number1 + number2 + number3) / 3.0;    // calculates the average

    cout << "The average of the three integers is: " << average << endl;

    system("PAUSE");
    return 0;
}    // end main( )

For now, notice how each executable statement in the program is ended with a semi-colon. Every executable statement must always be terminated with a semi-colon, which signals that it is the end of the statement. Any code placed after // will not affect the code; // is used for comments and documentation. Also notice that text is always enclosed in parentheses. Let's dig deep into the code to find out why you need to use certain code statements.

  • cout - console output - It is simply letting the compiler know that something is being sent into the output stream (normally the screen)
  • <<</code> - insertion operator - cout and the insertion operator go hand and hand; you must use it whenever you issue a cout command
  • cin - console input - It is simply letting the compiler know that something is being sent into the input stream (normally into the memory of a computer)
  • >> - extraction operator - cin and the extraction operator go hand and hand; you must use it whenver you issue a cin command
  • endl - end line - basically the same as pressing the return key in a text editor; returns down to the next line

system("PAUSE") - basically specifically designed for Dev's compiler; simply pausing the system during execution of the program so the user can interact with the program through a seperate screen module

Let's take a look at the structure of a C++ program. A program is made up of one or more functions. A function is a subprogram that performs some specific task and perhaps returns a value to the statement that called (invoked) it. The one required function for all programs is main ( ); it serves as the starting point for execution of a program. The main ( ) function may then call other functions which may call other functions and so on. A problem is broken down into smaller pieces from the use of functions.

Definition

function - a subprogram that performs some specific task and perhaps returns a value to the statement that called it.

The following is an outline of a C++ program in the order in which they occur.
    a) an "overview" of program (documentation); comments
    b) #include statements
    c) function prototypes [you don't need a prototype for the main ( )]
    d) main ( ) definition
    e) definitions of other functions

Documentation
The first part of any program should always contain detailed documentation concerning the program. It should include the program's overall purpose, the name of the programmer who wrote the code, the date the program was last updated, and any other information that you or other programmers may need to know in case you or someone else refers to the program code in the future. Comments can be inserted into program code in two ways:

    a - for single line comments, use: // your comments
        Anything placed after ( // ) is considered to be a comment.
    b - for multiple line comments, use : /* your comments */
        Anything placed between ( /* ) and ( */ ) are also considered comments.

#include Statements
The include section holds C++ include files which basically allow the execution of particular C++ code to be compiled and executed. The include files are different for every compiler, but #include <iostream.h> and #include <stdlib.h> are normally required for most compilers. The include statements are installed with the compiler, and it is your responsibility to call upon a statement if you need it. You are also allowed to create include files, but we won't get into that right now.

NOTE: The area after the include statements and before the main ( ) function is called the global area of program code.

Function Prototypes
Function prototypes are placed after the include statements. Every function, except main ( ), must have a function prototype, which is described in detail below.

main ( )
The main ( ) function is the starting point of execution in a C++ program. All other functions and program flow executable statements are basically branched from the main ( ) function.

Definitions of Other Functions
The use of functions in C++ is very important to learn. Just like everything else in C++, functions must be declared, and they have a specific form, which is as follows:

    return-type function_name ( parameter list )
    {
        statement(s)
    }


For now, just focus on the form of functions because I haven't mentioned anything about return-types, variable names, or parameters. We will cover those aspects later.

The function heading is simply:

    return-type function_name( parameter list )

The function body is simply:

    {
        statement(s)
    }


The function definition is simply the function heading plus the function body (the full function).

A function prototype looks exactly the same as the function heading with the addition of a semi-colon at the end.

    return-type function_name( parameter list );

Function prototypes are placed after the include statements but before the main ( ) function in a program. Remember that main ( ) is the only function that dosen't need a prototype; prototypes are required for all other functions. The following is an example of a function that accepts three integers (as input) and returns the average of the three values.

    int getAverage( int num1, int num2, int num3)
    {
        int average;
        average = (num1 + num2 + num3) / 3.0;
        return average;
    }    // end getAverage ( )


The function broken down:

function return type: int
function name: getAverage
parameters: num1, num2, num3

The following is another example of a function. This function will accept a fahrenheit temperature (as input) and will convert the temperature into the equivalent Celsius temperature and then return the Celsius temperature.

    float convertFahrToCelsius( float fahrTemp )
    {
        float celsiusTemp;
        celsiusTemp = ( fahrTemp - 32 ) / 1.8;
        return celsiusTemp;
    }    // end convertFahrToCelsius ( )


It obvious that in order to use this function, we need a complete program. A program whose only purpose is to test one or more functions is usually called a driver program. A function prototype is needed because everything in C++ must be declared before you can use it. In other words, it tells the compiler the name of the function, the return data type, and the number and type of parameters. This is everything a compiler needs to determine if you are using a function properly.

In C++, literals are exactly what they are. They have no special internal meaning. A literal can be a number, a letter, or a string (group of letters). 17, 'a', "name", "mike", "c++", 452, -112, etc.

Variables have an associated memory location and can be modified. For example, say you have a program that will calculate the average of three numbers. In the program code you should have four variables: num1, num2, num3, and average. During execution of the program, the compiler will give each of the variables a memory location in the memory of the computer. If the variables are not set to a default value in the program, as they are placed into memory, they will be assigned some type of garbage value until that value is changed during execution of the program.

Identifiers are the names you give variables, functions, etc. In C++, an identifier must begin with a letter or an underscore and further characters must be letters, underscores, or digits. Examples are STAR_TREK, THX792b4, FifthAvenue, etc.

So now you've seen bits and pieces of a program written in C++. Read on further to take a peek at the different data types...

Data Types

When declaring variables, functions, etc., you will need to specify a data type. That is the reason why you declare something. You are letting the compiler know what type of data it is going to be working with. In C++, data is either integral (integers and characters) or floating-point. Characters are considered integral because the character values will eventually be converted into an ASCII value. There is also a boolean type, which I won't mention too much about in this tutorial. Boolean types can be used when using logical data; when something can be either true or false. A 1 is considered true, and 0 is considered false.

There are several possible sizes and for some of these data types there is a choice of unsigned or signed types. Signed simply means that the data can be negative or positive. Unsigned means the data will be strictly positive. In the following list, the sizes are representative only (compiler dependent).

char 1 byte -128 to 127
unsigned char 1 byte 0 to 255
int 2 bytes -32,768 to 32,767
unsigned int 2 bytes 0 to 65,535
long or (long int) 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295
float 4 bytes 3.4 x 10^-38 to 3.4 x 10^38
double 8 bytes 1.7 x 10^-308 to 1.7 x 10^308
long double 10 bytes 3.4 x 10^-4932 to 3.4 x 10^4932



Note that integer values may be given in decimal, hexadecimal, or octal. Any value that begins with 0x or OX is a hexadecimal number. Any value that begins with 0 is octal. Also note that floating point values may be given in scientific notation. For example, the value 2.693 x 10^23 can be written as 2.693E+23.

The form for declaring a variable is as follows (will see this in next section also):

    data-type identifier;
        Ex: int num1;


Initialization is different from declaring because you declare the variable and also give it a value:

    data-type identifier = value;
        Ex: int num1 = 123;


You can also initialize a variable constant. The form for named constants is:

    const data-type identifier = value; (where value is a literal)
        Ex: const int MAXSIZE = 450;


Why would you want to use named constants? For one, it can help you avoid errors. By declaring something constant, the value of the variable will never be changed during program execution. Secondly, it can make programs easier to modify or correct. Let's say you have a program that processes the income statements for 30000 people, but there is a major lay-off and it is now cut back to 25000. If you had a constant variable for the maximum number of people, it would be very easy to edit the code. Finally, you get away from using "magic numbers", which are numbers that you see in programs and have no clue where they came from.

Note: constants are generally placed after the include statements but before anything else in a program (in the global area).

Now you have data types under your belt. Read on to actually learn how to assign values to variables and how to manipulate data with arithmetic operators...

Arithmetic Operators & Assignment Statements

Assignment Statements
An assignment statement is fairly simple to understand. It is a way of assigning a value to a variable; it stores a value in the indicated location. The form of an assigment statement is:

    variable = expression;


Because you are specifying a variable, the variable must be declared so the compiler knows what type of data will be involved. The expression should therefore match the data type of the variable being assigned to it. Some programmers prefer to use two descriptive words when dealing with these types of statements: declarations and initializations. A declaration is when you declare something. When you initialize something, you declare it and give it a value.

An example of a declaration:    int x;
An example of an initialization:    int y = 100;


Arithmetic Operators
For arithmetic expressions, the fundamental operators are as follows:

    +,- (unary and binary forms: addition/subtraction; positive/negative)
    * (multiplication)
    / (division)
    % (modulus or MOD) ---> returns the integer remainder of a division

NOTE: / will result in an integer value if both operands are integers; otherwise, it will result in an floating point value.
NOTE: % is defined for integers only.

Examples:

        int x = 25;
        int y = 7;
        cout << x / y << endl;        ---> 3
        cout << x % y << endl;        ---> 4
        cout << y % x << endl;        ---> 7

NOTE: the only possible values for an expression of the form x % y are: 0,1,2,...,y - 1

Let's take a look at some examples of code segments you might need when finding a solution of a particular problem.

Example 1: Suppose a line is 76 inches long. Convert this line in dimensions of feet and inches.

    feet = 76 / 12;
    inches = 76 % 12;

Example 2: To determine if a given integer is odd or even.

    number % 2 == 0
    if true ---> number is even
    if false ---> number is odd

Example 3: To determine if a given number is divisble by 3.

    number % 3 == 0
    if true ---> yes
    if false ---> no

NOTE: == is a relational operator which is discussed in later articles [see Logical Expressions (section 3)]

Hopefully you can see how division and modulus can be used for solving problems. The following are some common errors that many beginning programmers run into when programming.

Common Errors:

  1. x = 29 % 4.8;
    Error: the compiler will display something along the lines of "invalid use of floating-point". Remember modulus is defined only for integers.
  2. p + 7 = x + 3;
    Error: the compiler will display something along the lines of "Lvalue required", which means the compiler must find a memory location when assigning values to a variable. In C++, = is an operator; it does not imply equality.

C++ also provides some "shortcut" operators that come in handy when programming. The increment operator, ++, adds 1 to a variable. The decrement operator, --, does the opposite and subtracts 1 from a variable.

Example:

    n = n + 1 is equivalent to n++ and ++n; n = n - 1 is equivalent to n-- and --n

n++ and n-- are called post-increments, which mean they are performed after anything else in the statment. ++n and --n are called pre-increments, which mean they are performed before anything else in the statement.

Example:

    int x = 7;
    int y = 4;
    cout << x++ * --y << endl;     --> 21
    cout << x << " " << y;         --> 8    3


C++ also has shorthand assignment operators or sometimes called compound assignment operators. In general, n += (expression) implies n = n + (expression); n -= (expression)implies n = n - (expression); n *= (expression) implies n = n * (expression); n /= (expression) implies n = n / (expression); n %= (expression)implies n = n % (expression).

n = n + 1    -->    n++    -->    ++n
n = n - 1    -->    n--    -->    --n


Well you now know how to use arithmetic operators and assignment statements, but you might not know exactly how these operations are evaluated in statments. Read on to find out which operators have precedence over others...

Operator Precedence & Operator Associativity

Operator precedence and operator associativity are both very important to understand. The best way to understand these concepts is to examine some examples.

Operator Precedence:

    unary +, - (high precedence)
    *, /, %
    binary +, - (low precedence)

Operator Associativity:

Associativity may be left associative (left to right) or right associative (right to left). All arithmetic ops are left associative; assignment ops (+=, -=, *=, /=, %=, =) are right associative.

Let's examine some examples.

Example 1:

    int a = 6, b = 5, c = 9;
    cout << a + b * c;        --> 6 + ( 5 * 9 ) = 51
    cout << a * b % c;        --> ( 6 * 5 ) % 9 = 3


Example 2:

    int a = b = c = d = 6;    --> intializes a, b, c, and d to a value of 6

Example 3:

    x = y = 5;
    a = 8;
    b = 5
    c = a * b / 3 + a / x;
    cout << c;                --> ( 8 * 5 ) / 3 + ( 8 / 5 ) = 13 + 1 = 14

    c = 9 + a % b;
    cout << c;        --> 12

    c = 10 / 3 * ( 2 + b )
    cout << c;            --> 10 / 3 * ( 7 ) = 3 * 7 = 21;


Example 4:

    17 / 2 / 3 - 125 % 5        --> ( ( 17 / 2 ) / 3 ) - ( 125 % 5 ) = 2

    2.5 * 6 + 3 / 2.0        --> 15.0 + 1.5 = 16.5
    2.5 * ( 6 + 3 ) / 2.0        --> 22.5 / 2.0 = 11.25


Now that we have covered the precedence of operators and operator associativity, we can now move on to something that occurs during assignment statements, sometimes without the programmer asking for it and sometimes by the programmer specifically asking for it. Read on for more about type conversions...

You might also like...

Comments

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“There are 10 types of people in the world, those who can read binary, and those who can't.”