(Q) Static typingΒΆ

Goal: I will execute C++ code to learn how static typing works.

Instructions: Create a new project in Qt Creator.

In Python, the name of the main program is usually main, but we could use any other name. In C++, the name of the main function must be main, because the compiler starts program execution from a function the name of which is main.

Therefore in PyCharm, it is easy to implement several tasks in the same project to the files of their own. In Qt Creator, a project means a whole that consists of code files. Files under a project belong to that programming project.

You can find the answers to the following questions by modifying a program and then testing it to see what happens.

* Changing the active project:

Now you have two projects open in Qt Creator at the same time. One of the projects is the active one (the name of the project is written in bold in Projects window). If you click compile or run buttons, the action concerns the active project. How can you switch the active project?

* Type conversion 1:

Write the following lines to your program:

bool b = 1 + 2;
cout << b << endl;

the latter of which just makes easier to study the topic in more detail. What happens, when you try to compile and run the program?

* Type conversion 2:

Write the following lines to your program:

if ( 1 + 2 ) {
    cout << "Hip" << endl;
}

What happens, when you try to compile and run the program?

* Type conversion 3:

Write the following line to your program:

string s = 3;

What happens, when you try to compile and run the program?

* Type conversion 4:

Write the following lines to your program:

int i = -1;
unsigned int ui = 1;
cout << ui << endl;

if ( ui == i ) {
    cout << "Hello" << endl;
}

What happens, when you try to compile and run the program?

* Type conversion 5:

Write the following lines to your program:

int i;

if ( i = 0 ) {
    cout << "Hurrah" << endl;
}

Note that the condition of the if structure has not relational operator == but assignment operator =. So, we are doing something stupid.

In addition, you need to know that the assignment operator is indeed an operator in C++, as said previously. This means that it is possible to chain assignments as:

i = j = k = 0;

Previous line first assigns k = 0, the result of which is 0. Next the result of assignment k = 0 is assigned to variable j, and so on. What happens, when you try to compile and run the program?

* Static typing:

So, what is meant with static typing in practice?