Migrating from Pascal and Java to C++

Eric Chown
August, 1998

This document provides a gentle introduction to C++ if you have some Pascal or Java programming experience. It is also a work in progress, and all comments and suggestions for improving it are most welcome! Send them by e-mail to me at echown@polar.bowdoin.edu. Special thanks to Allen Tucker for providing the basis for this document.


Contents

  1. Overall Program Structure
  2. Data Types and Variable Declarations
  3. Statements
  4. Methods (Functions and Procedures)
  5. The String Class
  6. Stream Input and Output
  7. Example: Making a Standalone Application

C++ is implemented at Bowdoin on both the Linux machines and the Macs. Information about running C++ programs under CodeWarrior on the Macs can be found in the document Writing CodeWarrior C++ Applications.


1. Overall Program Structure

A C++ program designed as a stand-alone application has a basic structure much like that of a Pascal program. The best analogy to Java is that in C++ there is a main function which allocates programming resources, rather than a collection of objects which tend to work interactively. The program has a series of statements embedded in a function called "main," a collection of auxiliary function declarations, and a collection of global variable declarations that are used by the statements in the program. The function "main" is the first to be executed when the program begins running. The syntax of a complete stand-alone C++ application program is as follows:

#include <iostream.h>

<variable declarations>

<function declarations>

void main () {

  <statements to execute when the program begins running>

}


The "include" statements at the beginning of the program indicate specific function libraries to be used by the program. The include statement here suggests that most C++ application programs use some of the stream/file input and output methods from the "iostream.h" library. The #include directive tells the compiler to look for a specific file (in this case iostream.h) and read in the contents of that file as though you had typed it in yourself. There are numerous standard files available to be included (discussed below), and programmers can also develop their own. In this way C++ is more like Java than Pascal, in that it is designed to be fairly portable. That is, programs can often be designed as components of other programs. In addition, the C++ program may declare its own functions to supplement those that are provided by these libraries.

Scope of Declarations

The scope of a declaration in a C++ program is the range of statements that may reference the declared variable or function. The scope of the variables and functions identified in the declarations above includes the entire program. As we get more advanced in C++ we'll see scoping rules similar to the scoping of objects in Java, with public and private scoping rules. As we shall see, all functions (including the function "main") may declare additional variables for local use, in which case their scope is limited to the body of the function in which they are declared. Variable names must be unique within the function where they are declared. Moreover, variable names are case sensitive, so that (for instance) the names "sum," "Sum," and "SUM" refer to distinct variables.

Unlike Pascal, C++ function declarations may not be nested. Thus, the structure of a C++ program is relatively flat. When two variables have the same name, their scopes must be mutually exclusive. Thus, if a variable declared locally within a function has the same name as another variable declared among the <variable declarations>, all references to that name from within that function are treated as references to that local variable. In general, no two variables declared within a single function should have the same name.

Comments

Double slashes (//) in a C++ program indicate that the rest of the line is a comment. In addition you can enclose comments using /* and */. This serves the same purpose as the braces { and } in Pascal programs.

The Standard C++ Libraries

The predefined C++ functions are grouped into a small number of standard files. For instance, input and output operations are performed through functions in the file iostream.h, which is summarized in the next section. Here's an overview of the major libraries in C++. To access these files use the #include directive and enclose the filename in angle brackets like this:

#include <iostream.h>

The angle brackets let the compiler know that these are standard libraries. To include your own files, use quotes like this

#include "myfile.h"

iostream.h
contains stream and file I/O classes.
math.h
contains math functions such as sin and cos.
string.h
contains routines that deal with pointers, particularly as related to string processing.


2. Data Types and Variable Declarations

There are two types of variables in C++, "primitive types" and "pointer types." Primitive types are passed by value when used as arguments in function calls, while pointer types are passed by reference. Below are the primitive data types in C++, along with some explanations:

Primitive Type          Bytes (typical)          Stores
-------------------     -----------------------  -------
char                         1                   character
short                        2                   integer
int                          4                   integer
long                         4                   integer
float                        4                   floating-point
double                       8                   floating-point
long double                  8                   floating-point

For most applications int and double are used for integer and floating-point types respectively.

The char data type supports ASCII characters such as A, b and punctuation symbols such as ! and #. It is important to understand that every character has a number that represents it. For example the character A is represented by 65. C++ requires you to enclose characters in a pair of single quotation marks. For example

'A'

'?'

Most characters appear in a C++ string as they appear on the keyboard; the following characters have escape sequences when they are typed as part of a C++ string:

Character               Escape sequence
-------------------     ---------------
Backspace               \b
Horizontal tab          \t
New line                \n
Form feed               \f
Carriage return         \r
Double quote            \"
Single quote            \'
Backslash               \\

Here are some example C++ variable declarations, alongside their Pascal and Java counterparts:

C++              Pascal                 Java
------------------------------------------------------
float x, y;           var x, y: real;        float x, y;
char c;                      c: char;        char c;
int i, j;                 i, j: integer;     int i, j;

Pointer types in C++ are arrays and "objects." The idea of an object is similar to the idea of a variable -- an object has a state (i.e., a value) and an associated set of operations that can be performed on that value. A String variable in C++ is an example of an object. A String's state is its current value (i.e., its sequence of characters between quotes), to which certain string operations (e.g., concatenation, selecting a substring, etc.), called functions, can be applied. Declaring an array or String variable in C++ is somewhat more general than in Pascal (and very similar to Java), as the following examples show.

C++                                    Pascal
-----------------------                 -------------------------------
int A[5];                               var A: array[1..5] of integer; 
float B[4] = {3, 6, 9, 2};
char s[] = "Hello World!";              var s: string;
                                        ... s := 'Hello World';
char t[];

The first line declares an array A, which in C++ is indexed from 0 to 4 (not 1 to 5, as is usual in Pascal). So A[0] refers to the first element in A, and A[4] refers to the last. The second line shows how in C++ a declaration can initialize the values in a variable or array. The third line illustrates the declaration of a String variable in C++, along with an initial value assignment. Note that there is no explicit type for strings in C++, rather they are implemented as arrays of characters. Next we compare the same statements in C++ to their Java counterparts.

C++                                    Java
-----------------------                 -------------------------------
int A[5];                               int A[] = new int[5];
float B[4] = {3, 6, 9, 2};              float B[] = {3, 6, 9, 2};
char s[] = "Hello World!";              String s[] = {"Hello World!"};

While standard Pascal doesn't formally support strings, most of its implementations do, as shown in the example on the right. In C++, objects are "pointer types." Thus, like the array A, the String s is created as a pointer to a dynamically allocated block of storage in a memory area called the "heap." If passed as an argument to a function, the array A or the String s will be passed by reference. We will go into what this all means in detail in class.

The default value for pointer types is null. For instance, the String variable t declared above, with no initial value, is initially a null pointer. Later, when the string is assigned a value, that value will be dynamically created in the heap and t will reference, or "point to," that value.


3. Statements

C++ statement types include expressions (including assignments), loops, conditionals, switch, break, and continue statements.

Assignments

The assignment operator is = (which, by the way, should not be used as a comparison operator).

C++/Java                              Pascal
-----------------------                 -------------------------------
i = i + 1;                              i := i + 1;
i++;
++i;

Note that the second and third examples are commonly-used variations of the first. That is, the ++ operator in C++ is often used to increment a variable by 1. The placement of the ++ relative to the variable tells the compiler when the increment should occur. Use caution when using these within expressions.

Other Expressions, Operators, and Mathematical Functions

Here is a summary of the principal C++ operators, in order from highest to lowest precedence:

C++/Java                                Pascal
-------------------------               -------------------------------
++ -- + - ! ( <type> )                  n/a n/a + - not n/a
* / %                                   * / div mod
+ -                                     + - 
<= >= < >                               <= >= < >
== !=                                   = <> 
&&                                      and
||                                      or
= (assignment)                          :=
Note that == is the equality comparison operator in C++, not = (which is assignment). Also, note that / gives an integer quotient when both operands are integers, and a decimal quotient otherwise; so it acts sometimes like div in Pascal. Here is an incomplete summary of the functions available in math.h

C++                                    Pascal
-----------------------                 -------------------------------
fabs atan cos exp log                   abs arctan cos exp ln
acos asin ceil floor                    n/a
pow                                     n/a
n/a                                     odd ord pred succ trunc
sin sqrt tan                            sin sqrt tan

Conditionals
C++/Java                               Pascal
-----------------------                 -------------------------------
if ( <condition> ) {                    if <condition> then begin
   <statements>                              <statements>         
else {                                  else begin 
   <statements>                                <statements>
  }                                          end
}                                       end

The else clause is optional, as are the braces {} when the group of <statements> contains only one statement.

Loops
C++/Java                               Pascal
-----------------------                 -------------------------------
for (i=1; i<=n; i++) {                  for i:=1 to n do begin
   <statements>                            <statements>
}                                       end

while ( <expression> ) {                while <expression> do begin
   <statements>                            <statements>   
}                                       end
Switch and Break
C++/Java                               Pascal
-----------------------                 -------------------------------
switch ( <expression> ) {               case <expression> of
  case <value1>: <statement1> ;            <value1>: <statement1> ;
       break;
  case <value2>: <statement2> ;            <value2>: <statement2> ;
       break;
   ...                                     ...
}                                       end

Note that the break statement must explicitly end each of the case alternatives in the C++ code if the same meaning is to be conveyed as in the Pascal version. Leaving out the break statement between two cases is sometimes useful when a different effect is needed.


4. Functions (Functions and Procedures)

A C++ "function" is similar to a Pascal function or procedure and a Java method. The main difference from Java is that functions are all considered public and therefore do not have to be explicitly declared that way.

C++                                    Pascal
-----------------------                 -------------------------------
<type> <name> (<params>) {              function <name> (<params>) 
   <local variable declarations>            <local variable declarations>
                                          begin
   <statements>                             <statements>
   return <expression> ;                    <name> := <expression>
}                                         end;

The type returned by a function may be any primitive or pointer type, or else void. A function with a void return type is comparable to a Pascal procedure. If the return type is not void, the "return" statement should be used to send the returned value to the call. As shown above, this is similar to a Pascal function, in which the result is returned by making an assignment to the function's <name>.

Remember, all parameters with primitive types are passed by value in a function call, while all parameters with pointer types (arrays and objects) are passed by reference. Thus, Pascal's var parameter can always be simulated in C++ by using a parameter with a pointer type.

A function may be called in one of two different ways; in the conventional way or in "dot" notation common in Java objects. The conventional call is like an ordinary function call in Pascal or C/C++. For instance, a call to the function 'sqrt'

sqrt(x) 

returns the square root of the value of the argument x. On the other hand, the call to the function 'equals'

s.equals("Hello World!")

where s is a String, returns the boolean value true or false depending on whether the current value of s is identically "Hello World!".

A general rule of thumb for whether or not to use the "dot" notation is guided by whether or not the variable to which the function is being applied is a member of that function's class. In the above examples, for instance, the variable x has primitive type (presumably float or double), but the function 'sqrt' is a member of the Math class. Thus, the dot notation is not used. In the second example, the "dot" notation is used because the variable s is a member of an object class, and so is the function 'equals.' We'll learn more about classes later. Invoking either the function 'sqrt' or the function 'equals' the wrong way, e.g.,

x.sqrt()
equals(s, "Hello World!")

will result in an error.


5. The String Class

Character strings are implemented in C++ by building upon the char class. The strcat function is used to concatenate two strings into one, while the strcmp function is used instead of "==" to test for equality between two String variables or expressions. Here are a few examples of the major actions on strings.

String Action                    Example
------------------------------   -----------------------------------
Declaration                      char *s;
Declaration and initialization   char *s = "Hello!";
Assignment                       s = "Goodbye!";
Comparison -- equality           if (strcmp(s,"Goodbye!")
Concatenation                    s = strcat("Goodbye Cruel", " World!");
Number of characters (length)    strlen(s)    returns 19 in this case

6. Stream Input and Output

C++ does not have built-in operators to do input and output. Instead it relies upon libraries. The model is based upon the idea of streams which are attached to devices. Devices can include the console, files, the keyboard, etc. In this section we summarize the basic facilities for reading and displaying values in C++.

The stream library provides two basic operators, >> and <<, for input and output respectively. When you include the iostream.h file it makes the standard console operators cout and cin available. Here is a code fragment which does both input and output:

int aNum;
cout << "Enter a number : ";
cin >> aNum;
cout << "You entered " << aNum;

The code declares an integer aNum, displays a prompt using cout, reads a value into the integer and displays the result.

To read input, a program has three options:


7. Example: Making a Standalone Application

Here is a stand-alone C++ program that will input a number and display a countdown from that number to 1 followed by the message "Welcome to C++!"

#include ;

void main()
{

        int n = 0;
        cout << "Enter an integer" ;
        cin >> n ;                       // read an input integer
        for (int i=n; i>0; i--)
          cout << i ;
        cout << "Welcome to C++!" ;
}

Note that the int variable i is declared at the point where it is first used, inside the for statement. We could have declared and initialized i outside the main function altogether, in which case it would be globally accessible to all functions inside the program (if there were others).

A roughly equivalent Pascal program for this problem is shown below, so that other correspondences and differences between C++ and Pascal can be identified.

program myfirst (input, output);

var i, n: integer;

begin
        n := 0;
        writeln('Enter an integer:');
        readln(n);                       { read an input integer}
        for i := n downto 1 do
           writeln(i);
        writeln('Welcome to Pascal!');
end.