Pascal to C++ Crash Course

Quick C++ Installation and Environment Configuration

The following steps are performed on Windows.

Using an IDE

You can refer to the following pages:

Using a Code Editor + Compiler + Debugger

You can refer to the VS Code page. The official Visual Studio Code website has documentation explaining how to configure C++. In general, VS Code is more convenient when used with extensions; see the official VS Code website.

A Quick Review of C++ Syntax

C++ programs all begin execution in the main function.

Braces mark the beginning and end of a block statement: { is equivalent to Pascal's begin, while } is equivalent to end.

As in Pascal, every C++ statement must end with a semicolon ;. However, a closing brace does not need a semicolon, and a period . is not written at the end of the program.

For comments, // denotes a line comment and /* */ denotes a block comment.

As usual, let's take a look at Hello World.

Hello World: The First C++ Program

#include <iostream>  // Import the iostream library.

int main()  // The main function.
{
  std::cout << "Hello World!" << std::endl;

  return 0;
}

Now compile and run it to see the result.

Brief Explanation

On the first line, #include <iostream> means importing the iostream library.

Pascal Library Files

Pascal does have library files; it is just that many students have never used them...

See the main on the third line? The program starts executing from main.

The next line is the most important one:

std::cout << "Hello World!" << std::endl;

std::cout is the output command. You may have seen some C++ programs write cout directly.

About the std:: Prefix

For the issue of the std:: prefix, see the note "What is std?" below this section.

The << in the middle vividly suggests flow; in fact, it indicates how output "flows". This line means that "Hello World!" is first pushed into the output stream, and then std::endl is pushed into the output stream.

std::endl is the output newline command. It is similar to Pascal's writeln, but C++ has no coutln. The difference between Pascal and C++ is that write('Hello World!') is equivalent to std::cout << "Hello World!", while writeln('Hello World!') is equivalent to std::cout << "Hello World!" << std::endl.

Here "Hello World!" is a string. In Pascal, strings use single quotes ', not double quotes, whereas C++ strings must use double quotes. Characters enclosed in single quotes have a different meaning in C++; this will be mentioned later.

All right, that should be enough explanation of Hello World.

Some students may ask what the return 0 later means, or what int main() means. Do not worry about it yet. When you first start writing programs, just use it as a template (it is written as a template here too). Since beginners do not use the parameters of main, there is no need to write int main(int argc, char const *argv[]).

Simple Exercises

  1. Try outputting a different string.
  2. Try learning about escape characters.

A+B Problem: The Second C++ Program

The classic A+B Problem.

#include <iostream>

int main() {
  int a, b, c;

  std::cin >> a >> b;

  c = a + b;

  std::cout << c << std::endl;

  return 0;
}

Note: There are many blank lines in the code; remove them if you are not used to that style.

Brief Explanation

std::cin is used for input (cin means C-in), and >> is similar to the output syntax.

Of the additional statements here, the two most important ones are a variable declaration statement and an assignment statement.

int a, b, c;

You may be used to declaring variables in Pascal like this:

var
a, b, c: integer;

C++ declarations begin directly with a data type name. Here, beginning with int (integer type) indicates that variables are about to be declared.

The next important statement is the assignment statement.

c = a + b;

This is a major syntactic difference between Pascal and C++: Pascal uses := for assignment, while C++ uses =; C++ uses == to test equality.

C++ also allows variables to be initialized at the time of declaration.

int a = 0, b = 0, c = 0;

Simple Exercises

  1. Rewrite the code, submit it to the OJ, and get AC.
  2. For more input and output syntax, refer to this section, and try to learn about C++ formatted output.

Closing Remarks and Next Steps

At this point, you have mastered some of the most basic concepts. What remains is to find the corresponding syntax and differing features in Pascal and C++.

Before that, however, it is strongly recommended that you read Variable Scope: Global and Local Variables.

Make good use of Alt+← and Alt+→ to go back and forward between jumps.

Syntax

Variables

Basic Data Types

C++ is broadly similar to Pascal. Common types include:

  • bool: Boolean type
  • int: Integer type
  • float: Single-precision floating-point type
  • double: Double-precision floating-point type
  • char: Character type
  • void: No type

C++ single quotes are specifically used to represent a single character (character type), such as 'a', while strings (arrays of characters) must use double quotes.

C++ also has many additional data types; see Fundamental types - cppreference.com.

Constant Declarations

const double PI = 3.1415926;

If you are unclear about macro expansion, it is recommended that you use constants instead of macro definitions.

Operators

See the Operators article directly. The appendix also provides a syntax comparison table for operators and mathematical functions.

Conditions

The if Statement

if (a = b) and (a > 0) and (b > 0) then
    begin
        b := a;
    end
else
    begin
        a := b;
    end;
if (a == b && a > 0 && b > 0) {
  b = a;
} else {
  a = b;
}

Boolean operations and comparisons:

  • and -> &&
  • or -> ||
  • not -> !
  • = -> ==
  • <> -> !=

Notes:

  1. and in Pascal and && in C++ have different precedence. C++ does not require parentheses around the condition.
  2. Pascal uses = to test equality and := for assignment; C++ uses == to test equality and = for assignment.
  3. If you write a = b instead of a == b inside the parentheses of an if statement, the program will not report an error. Instead, it assigns b to a, and the assignment expression a = b as a whole has the value of a after the assignment is completed.
  4. In C++, you do not need to think about whether to put a semicolon after end.
  5. In C++ Boolean operations, non-Boolean values can be converted to Boolean values automatically.
Common Pitfall

Pay special attention: Do not write = when you mean ==!

Since C/C++ syntax is more flexible than Pascal syntax, if you write if (a=b) in a conditional statement, the program will continue running normally because a=b has a return value in C++.

case and switch

They are not used very often, so they will not be covered in detail here.

Note that C++ has neither 1..n nor chained inequalities (such as 1 < x < 2).

Loops

The following three kinds of loops, implemented by these six pieces of code, perform the same function.

The while Loop

while is very similar. (The C++ code here is not a complete program; some framework boilerplate is omitted, and the same applies below.)

var i: integer;

begin
    i := 1;
    while i <= 10 do
        begin
            write(i,' ');
            inc(i); // or i := i + 1;
        end;
end.
int i = 1;
while (i <= 10) {
  std::cout << i << " ";
  i++;
}

The for Loop

C++'s for statement is very different.

var i: integer;

begin
    for i:= 1 to 10 do
        begin
            write(i, ' ');
        end;
end.
for (int i = 1; i <= 10; i++) {
  std::cout << i << " ";
}

Notes:

  1. The line for (int i = 1; i <= 10; i++){ contains many elements; there are three statements in the for.
  2. The first statement, int i = 1;, declares and initializes a local variable i. (This design is much more reasonable than Pascal's.)
  3. The second statement, i <= 10;, serves as the criterion for deciding whether the loop should continue.
  4. The third statement, i++, executes at the end of each iteration. It roughly corresponds to Pascal's inc(i). Writing ++i here has the same effect. For the difference between i++ and ++i, consult other resources.

repeat until and do while Loops

Note that repeat until and do while are different; compare the following code:

var i: integer;

begin
    i := 1;
    repeat
        write(i, ' ');
        inc(i);
    until i = 11;
end.
int i = 1;
do {
  std::cout << i << " ";
  i++;
} while (i <= 10);

Loop Control

break has the same purpose in C++ as in Pascal: it exits the loop.

continue also works the same way: it skips the current iteration and enters the next one (returning to the beginning).

Arrays and Strings

Variable-Length Arrays: The Standard-Library Vector Type

See the Sequence Containers page.

The C++ standard library provides vector, which is equivalent to a variable-length array; its header must be included before use.

#include <iostream>
#include <vector>  // Import the vector library.

int main() {
  std::vector<int> a;  // Declare vector a and define a as an empty vector object.
  int n;

  std::cin >> n;
  // Read a.
  for (int i = 0; i < n; i++) {
    int t;
    std::cin >> t;
    a.push_back(t);  // Put the input number t at the end of vector a; the operation is O(1).
    /* Index-based assignment cannot be used here because a is still empty when declared.
    Using `a[i] = t;` here is incorrect.
    */
  }

  // Print all numbers read into a.
  for (int i = 0; i < n; i++) {
    std::cout << a[i] << ", ";  // !Note that the first number in a is a[0].
    // If the index is out of bounds, an unknown value is returned (overflow) instead of an error.
  }
  std::cout << std::endl;

  return 0;
}

C++ accesses array elements similarly to Pascal, but there is one important difference: the first element of an array is a[0], whereas in Pascal the starting index can be chosen freely.

Strings: The Standard-Library String Type

See the string page.

The C++ standard library provides string. Some operations that can be performed on vector can also be performed on it, and its header must likewise be included.

#include <iostream>
#include <string>

int main() {
  std::string s;  // Declare string s.

  std::cin >> s;  // Read s.
  // Leading whitespace (spaces, newlines, and tabs) is ignored while reading; the input string ends at the next whitespace character.

  std::cout << s << std::endl;

  return 0;
}

C-Style Arrays

See the Arrays page.

If you need a variable-length array, use vector rather than a C-style array.

C-style arrays are closely related to pointers, so they will not be discussed further here.

Important Differences

Variable Scope: Global and Local Variables

C++ allows variables to be declared in almost any place. See Variable Scope.

When writing Pascal procedures/functions, it is easy to forget to declare a local variable i or j. The main program usually contains loops, so in many cases i and j become global variables. In this situation, operating on i in a procedure/function is very likely to cause errors. Even worse, if you forget to declare such a local variable, the compiler does not report an error and the program can run. (Many hard-to-find bugs come from exactly this.)

Therefore, when using C++, declare variables such as the i used in a loop. Do not use global variables when local variables will do; use local variables whenever possible. This way, you do not need to worry about collisions between variable names (such as i) in functions.

Additional Note

Pascal can avoid this problem to some extent. Following the C++ approach, let the main program only call procedures/functions, without declaring global variables such as i and j that are prone to name collisions. If a loop is needed, write another procedure and call it.

C++ Can Convert Types Automatically

int i = 2;
if (i) {  // i = 0 returns false; all other values return true.
  std::cout << "true";
} else {
  std::cout << "false";
}

This is not limited to converting int to bool; int and float can also be converted to each other. In Pascal, an integer can be assigned to a floating-point value, but not the other way around. C++ does not have this restriction.

int a;
a = 3.2;      // At this point, a = 3.
float b = a;  // At this point, b = 3.0.

Whether / means integer division or floating-point division is determined by the types of the divisor and dividend.

float a = 32 / 10;    // 32/10 gives 3 (integer division); a = 3.0
float b = 32.0 / 10;  // 32.0/10 gives 3.2; b = 3.2

pow(a, b) computes aba^b. This function returns a floating-point value; if it is used directly to calculate an integer power, automatic conversion means you do not need to worry about an error.

int a = pow(2, 3);  // Compute 2^3.

char and int can also be converted to each other.

char a = 48;              // ASCII 48 is '0'
int b = a + 1;            // b = 49
std::cout << (a == '0');  // true outputs 1

In fact, char and bool are essentially integer types in C++.

For details, see Implicit conversions - cppreference.com.

Many C++ Statements Have Return Values: Reading an Unknown Amount of Data

Sometimes you need to read until the input ends, for example, to find the sum of an unknown number of numbers (the data may span multiple lines) until the end of the file. One way to do this is:

End of File: EOF

EOF, the end-of-file marker, is entered as Ctrl+Z on Windows at the command line (followed by Enter), and as Ctrl+D on Unix-like systems.

#include <iostream>

int main() {
  int sum = 0, a = 0;

  while (std::cin >> a) {
    sum += a;
  }
  std::cout << sum << std::endl;

  return 0;
}

The principle is that in while (std::cin >> a), std::cin >> a returns false when there is an input problem or the end of the file is reached, causing the loop to stop.

Functions

C++ has functions but no procedures, with void serving that role; it has no function-value variable, but it does have return.

Here is a comparison of a Pascal function and a C++ function:

function abs(x:integer):integer;
begin
    if x < 0 then
        begin
            abs := -x;
        end
    else
        begin
            abs := x;
        end;
end;
int abs(int x) {
  if (x < 0) {
    return -x;
  } else {
    return x;
  }
}

In C++, declaring the function as int abs defines an abs() function whose return value has type int (integer); the function's return value is the value supplied by the return statement.

If you do not want a return value (that is, a Pascal "procedure"), use void. void means "empty" and returns nothing.

var ans: integer;

procedure printAns(ans:integer);
begin
    writeln(ans);
end;

begin
    ans := 10;
    printAns(ans);
end.
#include <iostream>

void printAns(int ans) {
  std::cout << ans << std::endl;

  return;
}

int main() {
  int ans = 10;
  printAns(ans);

  return 0;
}

C++'s return differs greatly from assigning a value to a function variable in Pascal. C++'s return returns a value, and once the statement has executed, the function ends; assigning a value to a function variable in Pascal does not leave the function itself, so execution continues. Thus, when Pascal needs to interrupt a function/procedure at some point, it needs an additional command, exit. C++ does not; if you need to interrupt execution at some point, you can use return directly. For example (I really could not think of a short and practical piece of code, so this will have to do for now):

#include <iostream>

void printWarning(int x) {
  if (x >= 0) {
    return;  // This statement is equivalent here to Pascal's `exit;`.
  }
  std::cout << "Warning: input a negative number.";
}

int main() {
  int a;

  std::cin >> a;
  printWarning(a);

  return 0;
}

In a certain sense, the preceding abs function is strictly equivalent only when written like this:

function abs(x:integer):integer;
begin
    if x < 0 then
        begin
            abs := -x; exit; // !Note this point.
        end
    else
        begin
            abs := x;  exit; // !Note this point.
        end;
end;
int abs(int x) {
  if (x < 0) {
    return -x;
  } else {
    return x;
  }
}
Special Reminder

In C++, exit exits the program. Do not type exit reflexively; use return!

C++ treats functions and procedures alike as functions, and does not even exempt main. For example, when you write int main, C++ treats main as a function of integer type, whose return value here is 0. This is a conventional rule: returning 0 means that the program exited normally.

You may have guessed that the parameters in main(int argc, char const *argv[]) are int argc and char const *argv[]; for their meaning, consult other resources.

Passing Parameters to Functions

C++ has no Pascal var keyword for changing passed parameters, but C++ can achieve the same effect using references and pointers.

var a, b: integer;

procedure swap(var x,y:integer);
var temp:integer;
begin
    temp := x;
    x := y;
    y := temp;
end;

begin
    a := 10; b:= 20;    
    swap(a, b);
    writeln(a, ' ', b);
end.
// Code using pointers.
#include <iostream>

void swap(int* x, int* y) {
  int temp;
  temp = *x;
  *x = *y;
  *y = temp;
}

int main() {
  int a = 10, b = 20;
  swap(&a, &b);
  std::cout << a << " " << b;

  return 0;
}

Note that the C++ code here involves pointers. Pointer issues are rather troublesome, so it is recommended that you read the relevant material.

// Code using references.
#include <iostream>

void swap(int& x, int& y) {
  int temp;
  temp = x;
  x = y;
  y = temp;
}

int main(int argc, char const* argv[]) {
  int a = 10, b = 20;
  swap(a, b);
  std::cout << a << " " << b;

  return 0;
}

Note that the C++ code here involves reference-related type issues. When using references to call some STL or template-library functions, you may encounter problems; in that case, you need to declare the type manually. You can consult the fifth edition of C++ Primer or online resources for details.

C++ has other ways to pass parameters to functions. One is to pass parameters directly through global variables; if you do not know how to use pointers, you can start with this approach. Its drawback, however, is that it does not use the stack to preserve data, so there is no way to pass parameters in a recursive function. (Unless you write the stack by hand; note that a manually implemented stack is also a way to break through the system stack limit.)

The C++ Standard Library and Reference Materials

Do not reinvent the wheel (unless it is for practice). Before implementing a feature yourself, first check whether a function or data structure for it already exists.

The C++ Standard Library

The C++ standard library's <algorithm> contains many useful functions, such as quicksort and binary search, which can be called directly. See the STL Algorithms page.

There are also STL containers, such as arrays, vectors (variable-size arrays), queues, and stacks, with many accompanying functions. See the Introduction to STL Containers page.

If you are looking for functions for string operations, see:

C/C++ pointers are very flexible; you can refer to the Pointers page. If you want to understand pointers thoroughly, find a book or reference manual and read it carefully.

Troubleshooting and Tips

C++ Language Resources

Afterword

By this point, many students may feel that this is not much of a crash course at all, and that many things have not been covered. That cannot really be helped.

Although this is meant as a crash course, topics such as converting strings to numbers and searching for characters in strings are not suitable for a concise crash-course post. If all of these were written out, it would become an introductory C++ tutorial, so make full use of this Wiki, reference manuals, and search engines.

One point should be made: although the discussion above is about C++ syntax, much of that syntax comes from the C language. The title would actually be better written as "Pascal to C/C++ Crash Course".

Pascal was a very popular language in the second half of the last century. It predates C, but as UNIX systems became widespread and Microsoft adopted C, Pascal became history. Pascal did continue to develop later; for example, the open-source Free Pascal compiler project added object-oriented features (the Delphi language). Apart from information competitions, Pascal has one use that other languages do not: compiler support for a very large number of old machines, such as the last century's Nintendo Game Boy. It also appears in many textbooks as pseudocode (Pascal-style pseudocode).

Finally, the Pascal community is actually quite small, while the C/C++ community is large, with extensive manuals and tutorials. Be sure to learn English well. There are many other programming languages in the world, and computer science and technology are about much more than information competitions and programming languages.

References for Pascal in This Article

Appendix: Syntax Comparison of Pascal and C++ Operators and Mathematical Functions

Only the most commonly used operators and functions are included.

Basic Arithmetic

PascalC++
Additiona + ba + b
Subtractiona - ba - b
Multiplicationa * ba * b
Integer divisiona div ba / b
Floating-point divisiona / ba / b
Moduloa mod ba % b

Logic

PascalC++
Notnot(a)!a
Anda and ba && b
Ora or ba || b

Comparisons

PascalC++
Equala = ba == b
Not equala <> ba != b
Greater thana > ba > b
Less thana < ba < b
Greater than or equal toa >= ba >= b
Less than or equal toa <= ba <= b

Assignment

PascalC++
a := ba = b
a := a + ba += b
a := a - ba -= b
a := a * ba *= b
a := a div b or a := a / ba /= b
a := a mod ba %= b

Increment/Decrement

PascalC++
Incrementinc(a)a++
Incrementinc(a)++a
Decrementdec(a)a--
Decrementdec(a)--a

Mathematical Functions

The <cmath> library must be included before use.

PascalC++
Absolute valueabs(a)abs(a) (integer)
Absolute valueabs(a)fabs(a) (floating point)
aba^bN/A1pow(a, b)
Truncate to integertrunc(a)trunc(a)
Round approximatelyround(a)round(a)

For other functions, see:

Footnotes

  1. Extended Pascal has a**b, but the Math library must be included. ↩

This content comes from OI Wiki: Pascal to C++ Crash Course. See the original for authors and revision history. AIOJ has adapted the formatting, in-site links, and resource paths.

Content is shared under CC BY-SA 4.0 and SATA license; additional terms are governed by the original notice. Thanks to the OI Wiki authors and contributors; per the SATA terms, please visit the OI Wiki repository and star it to show your support.