Get up to 80 % extra points for free! More info:

Lesson 3 - Variables and the type system in C++

Lesson highlights

Are you looking for a quick reference on C++ variables and type system instead of a thorough-full lesson? Here it is:

Creating an int variable (for whole numbers) and assigning a value 56 to it:

int a = 56;
cout << a << endl;
cin.get();

Reading text from the console using cin:

cout << "Write something: " << endl;
string input;
cin >> input;
cout << "You wrote: " << input << endl;
cin.get();

Reading numbers from the console:

cout << "Enter a number and I'll double it: " << endl;
int a;
cin >> a;
cout << (a * 2) << endl;
cin.get();

Would you like to learn more? A complete lesson on this topic follows.

In the previous lesson, Visual Studio and your first C++ console application, we learned how to work with Visual Studio, and created our first console application. In today's lesson, we're going to look at the so-called type system in C++. We'll introduce basic data types, and we'll work with variables. As a result, we'll create 4 simple programs, including a simple calculator.

Variables

Before we start with data types, let's make sure we understand what a variable is, if you're already familiar with programming, please excuse the short explanation. Surely, you remember variables from Math class (e.g. X), in which we could store some value, usually a number. A variable in IT is the same thing. It's a place in computer memory where we can store some data, e.g. a username or the current time. This place has a certain reserved size, different variable types have different sizes, which the variable can't exceed, e.g. integer number can't be bigger than 2 147 483 647.

A variable is always of some sort of data type. It can be a number, a character, text, etc. It depends on what we want to use it for. Before working with a variable, we have to declare it in order to specify what this variable will be called and of what data type it will be. The programming language will establish it in the memory and we'll be able to use it. Our computer knows, based on our declaration, how much memory the variable occupies and how to work with that piece of memory.

Type system

There are two basic type systems: static and dynamic.

In the dynamic type system, we're fully relieved from the fact that the variable has a data type at all. Obviously, the variables have one internally, but the language doesn't show it. Dynamic typing often goes so far that we don't have to declare variables at all. If we store some data in a variable and the language finds out that this variable had never been declared, it'll just create it automatically. In the same variable, we are able to store text, user objects or decimal numbers. The language will automatically change the inner data type according to the data we assign into the variable. Due to a smaller amount of code, development is usually faster in those languages. Some examples of languages with this kind of type system are languages like PHP or Ruby.

On the other hand, we have the static type system, which requires us to declare the variable type, and its type would be unchangeable from then on. Meaning that if we try to store a user object into a string, we'll get yelled at by the compiler.

C++ is a statically typed language. All variables must be declared as specific data types. The disadvantage to this is that, due to the declarations, the source code is a bit longer and it takes more time to write it. However, the main advantage is that before running, our compiler checks whether all data types match. Dynamic typing may look advantageous, but we can't automatically check a source code and if we expect a user object somewhere and we get a decimal number instead, the error will only be revealed during run-time and the interpreter would stop the program. C++ won't allow us to compile a program until it checks it for errors (this is yet another benefit to using compilers).

Let's make an example program so that you'll be able to apply this newly acquired knowledge. We will continue with the theoretical part of it all next time. Here are three basic data types:

  • Numbers: int
  • Real numbers (10.12, ...): double
  • Texts: string

Variable printing program

We'll go ahead and declare an integer variable, and name it: a, store the number 56 in it and print its content to the console. Create a new project and name it Output (we'll create a new project for each sample program). Don't forget to write the code inside the body of the main() function like we did last time, I won't add the main() function in here anymore.

int a;
a = 56;
cout << a << endl;
cin.get();

The first command declares a new variable, a, of the int data type. This variable will be used to store integers, i.e. whole numbers. The second command assigns a value to the variable using the "=" operator which we all know from math. The last command is already familiar to us. It will print the content of the variable a. The Console is smart and knows how to print numeric values as well.

Console application
56

The same code for a real number variable would look like this:

double a;
a = 56.6;
cout << a << endl;
cin.get();

It is almost the same as the code for an integer. The decimal separator will always be represented by a dot here. Even if your regional separator is a comma.

Parrot program

The previous program was a bit boring, let's try to respond to user input somehow. Let's write a program named Parrot. You can probably guess what it will do - it will repeat what the user has written (twice). We haven't tried to read anything from the console yet, but it's very simple. We have the cin object for that. We'll cover objects later, there's an entire, separate, course about them. For now, all we need to know is that the cin object can read data from the keyboard. In fact, we've already used it before, cin.get() waited for is to hit Enter in our first program:

#include <iostream>
#include <string>
using namespace std;

int main(void)
{
    cout << "Hi, I'm Lora, the virtual parrot, and I love to repeat!" << endl;
    cout << "Type something in: " << endl;
    string input;
    cin >> input;
    string output;
    output = input + ", " + input + "!";
    cout << output << endl;
    cin.get(); cin.get();
    return 0;
}

When using the string type we have to add #include <string> at the beginning of our code.

This one's a little more fun, right? :) The first two lines are self-explanatory (they just print text). On the third line, we declare a string input. Input will contain the return value of the cin object, i.e. whatever the user enters to the console. To make the code more understandable, we create another string variable for output. The interesting part of the code is when we assign the value to output using a process called string concatenation. We use the "+" operator to join several strings into one. As you can see, it doesn't matter whether it's a variable or it's an explicitly declared string in quotation marks in our source code. We assign the input to the variable, then a comma followed by space, then input again and finally an exclamation mark. Then, the program displays this variable and waits for the user to press any key before terminating.

Now, why is cin.get() shown twice at the end? We said that cin.get() waits for the Enter key. The problem is that cin only reads printable characters, so Enter is still in the input. Using the first cin.get() we remove the Enter and the second cin.get() waits for another Enter which has to come from the user once more.

I'd like to point out that cin reads only the first word. If we enter e.g. "Hello C++", we get just "Hello".

Console application
Hi, I'm Lora, the virtual parrot, and I love to repeat!
Say something:
cracker
cracker, cracker!

We can assign values to variables right in their declaration, so we could replace:

string output;
output = input + ", " + input + "!";

with:

string output = input + ", " + input + "!";

We could shorten the program in many other ways, but generally, it is better to use more variables and focus on clarity and readability than altering the code until we forget what the program was even supposed to do.

Doubler program

The doubler program will retrieve an input number, double it and display it. With the knowledge we currently possess, we could write something like this:

cout << "Enter a number and I'll double it: " << endl;
int a;
cin >> a;
a = a * 2;
cout << a;
cin.get(); cin.get();

Notice how we double the number a by assigning it to itself times two. We could make this code even shorter:

a *= 2;

The result:

Console application
Enter a number and I'll double it:
1024
2048

Simple calculator

Since we haven't worked with real numbers yet, let's program a simple calculator. It'll be very easy. The input will consist of two numbers, and the program will display the results for addition, subtraction, multiplication, and division.

cout << "Welcome to our calculator!" << endl;
cout << "Enter the first number: ";
double a;
cin >> a;
cout << "Enter the second number: ";
double b;
cin >> b;
double sum = a + b;
double difference = a - b;
double product = a * b;
double quotient = a / b;
cout << "Addition: " << sum << endl;
cout << "Subtraction: " << difference << endl;
cout << "Multiplication: " << product << endl;
cout << "Division: " << quotient << endl;
cout << "Thank you for using our calculator. Press any key to end the program." << endl;
cin.get(); cin.get();

Console application
Welcome to our calculator!
Enter the first number:
3.14
Enter the second number:
2.72
Addition: 5.86
Subtraction: 0.42
Multiplication: 8.5408
Division: 1.15441176470588
Thank you for using our calculator. Press any key to end the program.

We could also omit the auxiliary variables and compute the results when printing them:

cout << "Addition: " << (a + b) << endl;

In the next lesson, Solved tasks for C++ lessons 1-3, we'll talk some more about type systems, and introduce you all to more data types.

All of the programs are available for download in the attachment below. You should definitely try to create some programs similar to these, seeing as how you already have the knowledge necessary to do so! :)

In the following exercise, Solved tasks for C++ lessons 1-3, we're gonna practice our knowledge from previous lessons.


 

Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.

Download

By downloading the following file, you agree to the license terms

Downloaded 3x (1.09 MB)
Application includes source codes in language C++

 

Previous article
Visual Studio and your first C++ console application
All articles in this section
C++ Basic Constructs
Skip article
(not recommended)
Solved tasks for C++ lessons 1-3
Article has been written for you by David Capka Hartinger
Avatar
User rating:
No one has rated this quite yet, be the first one!
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn university David learned IT at the Unicorn University - a prestigious college providing education on IT and economics.
Activities