Skip to content

Pascal to C++ Crash Course

C++ Quick Installation and Environment Setup

The following procedures are performed on Windows systems.

Using an IDE

You can refer to the content in the following pages:

Using Code Editor + Compiler + Debugger

You can refer to the content in the VS Code page. The Visual Studio Code official website has documentation explaining how to configure C++. Generally, VS Code is more convenient with plugins; see the VS Code official website.

C++ Syntax Quick Reference

C++ programs start execution from the main section.

Braces indicate the beginning and end of a block statement: { is equivalent to begin in Pascal, and } is equivalent to end.

Note that, like Pascal, each statement in C++ ends with a semicolon ;. However, braces do not need a semicolon at the end, and the program does not need a period . at the end.

For comments, // indicates an inline comment, and /* */ indicates a block comment.

By convention, let's look at Hello World.

Hello World: First C++ Program

1
2
3
4
5
6
7
8
#include <iostream>  // Import the iostream library

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

  return 0;
}

Then compile and run it to see the result.

Brief Explanation

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

Pascal Library Files

Pascal actually has library files, but many students have never used them...

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

The most important statement next is

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

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

About the std:: Prefix

For questions about the std:: prefix, please see the note "What is std?" at the bottom of this section.

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

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

Here, "Hello World!" is a string. In Pascal, strings are enclosed in single quotes ' and cannot use double quotes, while C++ strings must use double quotes. Single quotes in C++ have other meanings for characters, which will be mentioned later.

Alright, that should explain Hello World sufficiently.

Some students might ask, what does the return 0 at the end mean? What does int main() mean? Don't worry about it for now. When starting to write programs, just treat it as a template (it's also written using a template here). Since parameters in main are not used at the beginner level, there is no need to write it as int main(int argc, char const *argv[]).

Simple Exercises

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

A+B Problem: Second C++ Program

The classic A+B Problem.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#include <iostream>

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

  std::cin >> a >> b;

  c = a + b;

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

  return 0;
}

Note: The code has many blank lines; you can remove them if you are not used to it.

Brief Explanation

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

Among the new statements, the most important ones are the variable declaration statement.

1
int a, b, c;

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

1
2
var
a, b, c: integer;

C++ declarations start directly with the data type name. Here, int (integer type) indicates that variables will be declared next.

Another most important statement is the assignment statement.

1
c = a + b;

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

C++ also allows variable initialization at the time of declaration.

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

Simple Exercises

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

Closing Remarks and Next Steps

Alright, by now you have grasped some of the most basic things. The next step is to find corresponding syntax and different features between Pascal and C++.

However, before that, it is strongly recommended to read Variable Scope: Global Variables and Local Variables.

Please make good use of Alt+← and Alt+→ for navigation.

Syntax

Variables

Basic Data Types

C++ is basically 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: Void type

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

C++ has many additional data types; please refer to Fundamental types - cppreference.com.

Constant Declaration

1
const double PI = 3.1415926;

If you are not clear about macro expansion issues, it is recommended to use constants instead of macro definitions.

Operators

Please refer directly to the content in the Operators article. The appendix also provides a comparison table of operators and mathematical function syntax.

Conditionals

if Statement

1
2
3
4
5
6
7
8
if (a = b) and (a > 0) and (b > 0) then
    begin
        b := a;
    end
else
    begin
        a := b;
    end;

1
2
3
4
5
if (a == b && a > 0 && b > 0) {
  b = a;
} else {
  a = b;
}

Boolean operations and comparisons:

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

Notes:

  1. The precedence of and in Pascal and && in C++ is different; C++ does not require parentheses around the condition.
  2. In Pascal, equality is = and assignment is :=; in C++, equality is == and assignment is =.
  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 will assign b to a, and the assignment expression a = b as a whole will have the value of a after the assignment.
  4. C++ does not require thinking about whether to add a semicolon after end.
  5. In C++ Boolean operations, non-Boolean values can be automatically converted to Boolean values.
Common Mistake Reminder

Pay special attention: Do not write == as =!

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

case and switch

Not used frequently, so not elaborated here.

Note: C++ does not have 1..n, nor does it have continuous inequalities (like 1 < x < 2).

Loops

The following three types of loops, six code snippets, achieve the same functionality.

while Loop

while is very similar. (The C++ code here is not a complete program; some framework templates are omitted, same below.)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
var i: integer;

begin
    i := 1;
    while i <= 10 do
        begin
            write(i,' ');
            inc(i); // or i := i + 1;
        end;
end.

1
2
3
4
5
int i = 1;
while (i <= 10) {
  std::cout << i << " ";
  i++;
}

for Loop

C++'s for statement is very different.

1
2
3
4
5
6
7
8
var i: integer;

begin
    for i:= 1 to 10 do
        begin
            write(i, ' ');
        end;
end.

1
2
3
for (int i = 1; i <= 10; i++) {
  std::cout << i << " ";
}

Notes:

  1. The line for (int i = 1; i <= 10; i++){ contains many statements; for has three statements.
  2. The first statement int i = 1; declares a local variable i and initializes it. (This design is much more reasonable than Pascal's.)
  3. The second statement i <= 10; serves as the criterion for whether the loop continues.
  4. The third statement i++ is executed at the end of each loop, roughly meaning inc(i) in Pascal. Writing ++i here is also the same. For the difference between i++ and ++i, please refer to other materials.

repeat until and do while Loops

Note that repeat until and do while are different. Compare the following code:

1
2
3
4
5
6
7
8
9
var i: integer;

begin
    i := 1;
    repeat
        write(i, ' ');
        inc(i);
    until i = 11;
end.

1
2
3
4
5
int i = 1;
do {
  std::cout << i << " ";
  i++;
} while (i <= 10);

Loop Control

break in C++ has the same function as in Pascal: to exit the loop.

continue is also the same: skip the current loop iteration and proceed to the next one (go back to the beginning).

Arrays and Strings

Dynamic Arrays: Standard Library Type Vector

Please refer to the content in the Sequence Containers page.

The C++ standard library provides vector, which is equivalent to a dynamic array. You need to import the library file before using it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#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 into a
  for (int i = 0; i < n; i++) {
    int t;
    std::cin >> t;
    a.push_back(t);  // Put the read number t at the end of vector a; this operation has O(1) complexity
    /* You cannot use subscript access for assignment here because the size of a is still empty at declaration.
       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: the first number in a is a[0];
    // If the subscript is out of bounds, it returns an unknown value (overflow) without reporting an error.
  }
  std::cout << std::endl;

  return 0;
}

Accessing array members in C++ is similar to Pascal, but with an important difference: the first item of the array is a[0], while in Pascal it can be specified.

Strings: Standard Library Type String

Please refer to the content in the string page.

The C++ standard library provides string, which has some operations similar to vector. It also requires importing the library file.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#include <iostream>
#include <string>

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

  std::cin >> s;  // Read into s;
  // When reading, all leading whitespace characters (space, newline, tab) are ignored. The string is read until the next whitespace character.

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

  return 0;
}

C-style Arrays

Please refer to the content in the Array page.

If you need dynamic arrays, use vector, not C-style arrays.

C-style arrays are closely related to pointers, so they are not elaborated here.

Important Differences

Variable Scope: Global Variables and Local Variables

C++ allows variable declaration almost anywhere. Please refer to Variable Scope.

When writing Pascal procedures/functions, it is easy to forget to declare local variables i or j. Since the main program usually has loops, in most cases i and j are global variables. Therefore, operations on i within procedures/functions are prone to errors. Worse, if you forget to declare such local variables, the compiler does not report an error, and the program can run. (Many hard-to-find bugs come from this.)

Therefore, when using C++, declare variables, such as i used in loops, do not use global variables; use local variables whenever possible. If you do this, you don't have to worry about variable name conflicts (like i) in functions.

Additional Note

Pascal can avoid this problem to some extent by imitating the C++ method: the main program only calls procedures/functions and does not declare global variables like i, j that are prone to name conflicts. If loops are needed, write another procedure to call.

C++ Can Automatically Convert Types

1
2
3
4
5
6
int i = 2;
if (i) {  // i = 0 returns false, others return true
  std::cout << "true";
} else {
  std::cout << "false";
}

Not only int to bool, but also conversions between int and float. In Pascal, you can assign an integer to a floating-point type, but not the other way around. C++ does not have this problem.

1
2
3
int a;
a = 3.2;      // Now a = 3
float b = a;  // Now b = 3.0

The distinction between / as integer division or floating-point division is determined by the types of the divisor and dividend.

1
2
float a = 32 / 10;    // 32/10 results in 3 (integer division); a = 3.0
float b = 32.0 / 10;  // 32.0/10 results in 3.2; b = 3.2

pow(a, b) calculates \(a^b\). This function returns a floating-point type. If used directly to calculate integer powers, due to automatic conversion, you don't need to worry about it reporting an error.

1
int a = pow(2, 3);  // Calculate 2^3

There are also conversions between char and int.

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

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

For details, please refer to the article Implicit conversions - cppreference.com.

Many Statements in C++ Have Return Values: Example of How to Read an Indefinite Amount of Data

Sometimes you need to read until the end of data. For example, to find the sum of an indefinite number of numbers (data can be multiple lines) until the end of the file, the implementation is:

End of File EOF

EOF, the end-of-file identifier, is input in the command line on Windows with Ctrl+Z (and then press Enter), and on Unix-like systems with Ctrl+D.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#include <iostream>

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

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

  return 0;
}

Implementation principle: In while (std::cin >> a), std::cin >> a returns false when there is an input problem or the end of the file is encountered, causing the loop to break.

Functions

C++ only has functions, not procedures, but has void. It does not have function value variables but has return.

Pascal function vs. C++ function example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
function abs(x:integer):integer;
begin
    if x < 0 then
        begin
            abs := -x;
        end
    else
        begin
            abs := x;
        end;
end;

1
2
3
4
5
6
7
int abs(int x) {
  if (x < 0) {
    return -x;
  } else {
    return x;
  }
}

In C++, the function declaration int abs defines the abs() function with a return type of int (integer). The function's return value is the value given by the return statement.

If you don't want a return value (i.e., Pascal's "procedure"), use void. void means "empty", returning nothing.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
var ans: integer;

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

begin
    ans := 10;
    printAns(ans);
end.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#include <iostream>

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

  return;
}

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

  return 0;
}

C++'s return has a very big difference from assigning a value to a function variable in Pascal. C++'s return returns a value, and after executing this statement, the function execution ends. In Pascal, assigning a value to a function variable does not exit the function itself; it continues execution. Therefore, if Pascal needs to interrupt a function/procedure at a certain point, it requires an additional command, namely exit. C++ does not need this; if you need to interrupt at a certain point, you can directly use return. For example (since it's hard to think of short and practical code, let's do it this way):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#include <iostream>

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

int main() {
  int a;

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

  return 0;
}

In a sense, the previous abs function should be strictly equivalent like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
function abs(x:integer):integer;
begin
    if x < 0 then
        begin
            abs := -x; exit; // !Note here
        end
    else
        begin
            abs := x;  exit; // !Note here
        end;
end;

1
2
3
4
5
6
7
int abs(int x) {
  if (x < 0) {
    return -x;
  } else {
    return x;
  }
}

Special Reminder

In C++, exit exits the program; do not accidentally type exit, use return!

C++ treats both functions and procedures as functions, not even sparing main. For example, writing int main, C++ treats main as an integer function, and the return value here is 0. It is a conventional practice; returning 0 indicates normal program termination.

Perhaps you have guessed that the parameters in main(int argc, char const *argv[]) are int argc and char const *argv[], but their meanings please refer to other materials.

Passing Parameters in Functions

C++ does not have Pascal's var keyword to change passed parameters, but C++ can use references and pointers to achieve the same effect.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
// 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: this C++ code involves pointer issues. Pointer issues are still troublesome; it is recommended to read related materials.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
// 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: this C++ code involves reference-related type issues. When using references to call some STL libraries or template libraries, you may encounter some problems, and you need to manually declare alias types. Specific information can be found in "C++ Primer" Fifth Edition or online materials.

C++ has other methods for passing function parameters. One is directly using global variables to pass parameters. If you don't know how to use pointers, you can use this method first. However, the drawback of this method is that there is no stack to save data, so it is impossible to pass parameters in recursive functions. (Unless you implement a stack manually. Note that manually implementing a stack is also a way to break system stack limitations.)

C++ Standard Library and References

Never reinvent the wheel (unless for practice). Before trying to write a function yourself, check if there is already a function or data structure available.

C++ Standard Library

The C++ standard library <algorithm> has many useful functions like quicksort, binary search, etc., which can be called directly. Please refer to the STL Algorithms page.

There are also STL containers, such as arrays, vectors (dynamic arrays), queues, stacks, etc., with many functions attached. Please refer to the STL Container Introduction page.

For string operation functions, see:

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

Error Troubleshooting and Techniques

C++ Language Resources

Afterword

Reading this, many students might think this is not first aid at all, and many things are not mentioned. That can't be helped.

Although it's for first aid, many things like how to convert strings to numbers, how to search for characters in strings, are not suitable for a concise first aid post. If all these were written, it would be a C++ introductory tutorial. So please make full use of this Wiki, reference manuals, and search engines.

It should be pointed out that much of the C++ syntax mentioned above actually comes from the C language. The title might be better as "Pascal to C/C++ First Aid Post".

Pascal was a very popular language in the latter half of the last century. It predates C, but with the popularity of UNIX systems and Microsoft's use of C, Pascal has now become history. Pascal had later developments, such as the Free Pascal open-source compiler project, adding object-oriented features (Delphi language). Besides its use in informatics competitions, Pascal has a characteristic that other languages don't have—compilation support for many old machines, such as the Gameboy, a Nintendo game console from the last century. Another use is as pseudocode (Pascal-style pseudocode) appearing in various textbooks.

Finally, the Pascal community is actually very small, while the C/C++ community is large, with many comprehensive help manuals and tutorials. It is essential to master English well. There are many, many programming languages in the world, and the discipline and technology of computer science are not just about informatics competitions and programming languages.

References for Pascal Language in This Article

Appendix: Pascal and C++ Operator and Mathematical Function Syntax Comparison Table

Only includes the most commonly used operators and functions.

Basic Arithmetic

Pascal C++
Addition a + b a + b
Subtraction a - b a - b
Multiplication a * b a * b
Integer Division a div b a / b
Floating-point Division a / b a / b
Modulo a mod b a % b

Logic

Pascal C++
NOT not(a) !a
AND a and b a && b
OR a or b a || b

Comparison

Pascal C++
Equal a = b a == b
Not Equal a <> b a != b
Greater Than a > b a > b
Less Than a < b a < b
Greater Than or Equal a >= b a >= b
Less Than or Equal a <= b a <= b

Assignment

Pascal C++
a := b a = b
a := a + b a += b
a := a - b a -= b
a := a * b a *= b
a := a div b or a := a / b a /= b
a := a mod b a %= b

Increment/Decrement

Pascal C++
Increment inc(a) a++
Increment inc(a) ++a
Decrement dec(a) a--
Decrement dec(a) --a

Mathematical Functions

Requires importing the <cmath> library.

Pascal C++
Absolute Value abs(a) abs(a) (integer)
Absolute Value abs(a) fabs(a) (floating-point)
\(a^b\) N/A1 pow(a, b)
Truncate trunc(a) trunc(a)
Round round(a) round(a)

For other functions, please refer to:


  1. Extended Pascal has a**b, but requires importing the Math library. ↩