C++ - Tutorial 002. Types, Variables and Arithmetic

C++, int, char, double, auto, nullptr

Each variable or expression has its own data type, for example, an declaration

int some_variable;

Indicates that the variable some_variable has an integer type int .

The declaration allows you to enter a variable in the program. This variable will have a certain type of data: integer, floating point, character in the case of basic data types, or custom type (data structure, class). The type of the variable defines the set of operations that can be performed on the variable. The declaration of a variable determines the allocation of the memory area that is required for it. And also the value of this variable, which from the computer's point of view will be a sequence of bits. The declaration of a variable also carries the name by which the programmer will refer to this variable in the program code.

In the above example, we have a variable that has a base integer type, with which arithmetic operations, comparison, assignment, etc. can be performed. Refer to the code in this code by this name by some_variable.

Fundamental data types

C++ provides the following fundamental types of data.

void

void - Is a data type with an empty set of values. It is incomplete and can not be set for objects and variables. However, it is possible to use pointers to type void, and also use void as the value returned by functions.

nullptr

nullptr - A special data type that is not itself a type as such, since it can not be set as a variable type, but it can be used as a null pointer. This type was introduced in the C++11 standard instead of the NULL null constellation defined by the implementation.

boolean

bool - A logical data type that takes the value either true or false. The size of the memory that this data type occupies may differ from 1 depending on the implementation in the target system. You can determine the size using the sizeof(bool) operator.

Character Types

char - Character types are used to represent text characters. The char character size is 1 byte, which allows to contain 256 different characters. The representation of all symbols can be found in the ASCII character table.

Symbolic data types are divided into three types:

  • signed char - signed type
  • unsigned char - unsigned type
  • char - A separate type that can be either signed or unsigned, depending on how the compiler code works.

The difference in the range of values, for example:

  • char -128...127
  • unsigned char 0...255

char can be used to store integer values that do not exceed one byte, but it is better to use Int for the integer values. But this is acceptable for embedded systems, with a tightly limited amount of memory.

There are also special types of character data:

  • wchar_t - Type for representing characters that do not have a single byte. This can be 32 bits for OSes that support UNICODE, or 16 bits for Windows notation for UTF-16.
  • char16_t - Type for presentation UTF-16, introduced in the C++11 standard.
  • char32_t - Type for the UTF-32 representation, introduced in the C++11 standard.

int

int - Integer data type. Modifiers can be used to determine the memory size allocated to this data type. If there are no modifiers, then it is guaranteed that the data type is at least 16 bits in size. However, on most 32/64 bit systems, it is guaranteed that the size occupied is at least 32 bits.

Modifiers

Sign modifiers

  • signed - Representation of a signed data type (if omitted, it is assumed by default)
  • unsigned - Unsigned data type representation.

Size Modifiers

  • short - The target type is optimized so that the size is at least 16 bits
  • long - The target type is optimized so that the size is at least 32 bits

The long modifier can be applied to the data type twice, which gives an optimization of the occupied variable space of at least 64 bits. This optimization is introduced in the C++11 standard.

long long int

Modifiers of size and sign can also be combined.

signed long long int

Floating Point Types

  • float - 32-bit floating-point data type.
  • double - 64-bit floating-point data type.
  • long double - Extended data type with a floating point, introduced in the C ++ 11 standard.

By the way, when developing software, you can notice using these data types, which developer started with pure C, and which one started with C++. Usage of float is typical for developers who started with C, double is typical for C++ developers.

Variables

Thus, variables can have the data types listed above, for example:

int a = 12;       // Integer type, the variable is 12
double b = 12.25; // Double-precision floating-point floating point type, variable is 12.25
char c = 'a';     // The character type, the variable is equal to the character "a"

Initialization of variables can be done in several ways.

double a1 = 2.3;
double a2 = {2.3};
double a3 {2.3};

Initialization with curly brackets was introduced in the C++11 standard. Initialization with curly brackets does not allow an implicit conversion, so the compiler will generate an error in the following cases.

int d1 = {2.3};
int d2 {2.3};

auto

Also, to declare variables in the C++11 standard, the auto specifier was introduced, which allows you to declare a variable without specifying a type. In this case, the type is output from the initializer, that is, the value that will be assigned to the variable. Thus, auto can not be used without an initializer, that is

// Correct, working variant
auto a = 14; 
// Not the right variant, not compiled
auto b;
b = 15;

The auto specifier can be used to declare lambda functions, or variables with a very complex declaration, which leads to a simplification of the program code.

Arithmetic

Above the basic types, you can perform various arithmetic operations:

x+y   // plus
+x    // unary plus
x-y   // minus
-x    // unary minus
x*y   // multiply
x/y   // divide
x%y   // remainder of the division

It is also possible to use comparison operations:

x==y  // equal
x!=y  // not equal
x<y   // less than
x>y   // greater than
x<=y  // less than or equal
x>=y  // greater than or equal

In addition to arithmetic and logical operations, the C++ functional offers more specific operations:

x+=y  // x = x+y
++x   // increment: x = x+1
x−=y  // x = x-y
−−x   // decrement: x = x-1
x∗=y  // x =x*y
x/=y  // x = x/y
x%=y  // x = x%y
We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.
Support the author Donate
KL

Переменная аuto доступна для использования в Qt?

Да, доступна. Только нужно использовать стандарт C++11, но насколько помню, Вы используете устаревшие стандарты C++, поэтому у вас вряд ли она будет работать.

Comments

Only authorized users can post comments.
Please, Log in or Sign up
How to become an author?

Contribute to the evolution of the EVILEG community.

Learn how to become a site author.

Learn it
Donate

Good day, Dear Users!!!

I am Evgenii Legotckoi, developer of EVILEG. And it is my hobby project, which helps to learn programming another programmers and developers

If the site helped you, and you want also support the development of the site, than you can donate by following ways

PayPalYandex.Money
Timeweb

Let me recommend you the excellent hosting on which EVILEG is located.

For many years, Timeweb has been proving his stability.

For projects on Django I recommend VDS hosting

View Hosting Timeweb
AS
May 26, 2020, 11:29 a.m.
Artem Sun-Dun-Chan

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
MN
May 25, 2020, 11:33 a.m.
Mitja Nagibin

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
f
May 25, 2020, 5:05 a.m.
falcon

C++ - Test 001. The first program and data types

  • Result:66points,
  • Rating points-1
Last comments
AL
May 29, 2020, 5:24 a.m.
Aleksandr Leonidov

Django - Tutorial 036. How to add authentication through social networks. VKontakte

Здравствуйте! После клика на ссылку авторизации выдает json словарь с ошибкой: {"error":"invalid_request","error_description":"redirect_uri is incorrect, check application redirect uri in …
May 28, 2020, 3:14 p.m.
Evgenij Legotskoj

Qt/C++ - Lesson 039. How to paint stroke in QSqlTableModel by value in the column?

Ну в моём примере, который в статье сработало так model->setData(model->index(1, 1), 7); Поскольку model->index(1, 0) - это индекс колонки id, которая скрыта, поэтому…
MA
May 28, 2020, 3:08 p.m.
Mihail A

Qt/C++ - Lesson 039. How to paint stroke in QSqlTableModel by value in the column?

Спасибо, завтра првоерю. А model->setData(model->index(1, 0), 7); Тоже заработало?
May 28, 2020, 3:06 p.m.
Evgenij Legotskoj

Qt/C++ - Lesson 039. How to paint stroke in QSqlTableModel by value in the column?

Да, метод data всё-таки влиял, я переписал его так и заработало удаление QVariant TableModel::data(const QModelIndex &idx, int role) const{ if (role == Qt::BackgroundColorRole) {…
May 28, 2020, 2:49 p.m.
Evgenij Legotskoj

Django - Tutorial 011. Adding comments to the site based on Django

Он более функциональный и его функционал объективно лучше поддерживается Django. Из первого, что приходит на ум: Это наличие полей типа Array Поддержка полей для JSON …
Now discuss on the forum
IP
May 29, 2020, 1:55 a.m.
Igor' Poroshin

QTablwView + QSqlQueryModel скрыть пустой столбец

Да, понятно. В данном случае лучше использовать серверную процедуру (если такие поддерживаются), в которой будет проверяться наличие всех пустых строк у нужного столбца и вызываться соответ…
RG
May 28, 2020, 6:21 p.m.
Rovshan Gurbanov

Сборка под старые версии Android

У меня SDK почти все версии есть, NDK есть версии 10, 17, 21. Но собирается приложение только с NDK v21 под Android версии 7.0 и выше Версия Qt у меня 5.14.2
May 28, 2020, 7:58 a.m.
Evgenij Legotskoj

Освобождение памяти QMainWindow::setCentralWidget

Да, соглашусь. Просто удаление происходит позже, а не сразу.
May 28, 2020, 5:43 a.m.
Mihailll

При подключении к git как указать пароль?

Нужно сделать ssh-keygen и потом полученый из файла код скопировать в ssh ключ в бикбакете
F
May 28, 2020, 1:42 a.m.
Fidan

QML

Да, проблема ушла, спасибо.
About
Services
© EVILEG 2015-2020
Recommend hosting TIMEWEB