C + + Tutorials (iii: Variables and Types)

Source: Internet
Author: User
Tags first string

———————————————————————— This series of tutorials for the translation of the official C + + tutorial, Click to refer to the original English, the level is limited, translation does not pass the place please understand! ———————————————————————— Variables and types

The actual use of the "Hello World" project in the previous chapter is quite questionable. We just write a few lines of code, compile them, and then execute the resulting program just to write a simple sentence on the screen. As opposed to the input and output of the sentence itself, it certainly will soon.

However, programming is not limited to printing simple text on the screen. In order to further deepen and be able to write programs that perform useful tasks and really save our work, we need to introduce the concept of variables.

Let's imagine that I let you remember the number 5 and also let you remember the number 2. You have stored 2 different values (5 and 2) in memory. Now, if I want you to add 1 to the first number, you should now keep the number 6 (ie 1 + 5) and 2 in memory. Of course, for example, we can also subtract these two numbers and get the result of 4.

The whole process above is like a computer capable of handling two variables. The same procedure can represent the following statements under C + +:

a = 5;b = 2;a = a + 1;result = a - b;

Obviously, this is a very simple example, because we only use 2 small integer values, but considering that your computer can store millions of digits, it also carries out complex mathematical operations.

Now we can allocate a piece of memory to define a variable.

Each variable requires a name that identifies it, and distinguishes it from other variables. For example, in the preceding code the variable name is a, B, and result, we can define the variable as any name we can think of, as long as they are valid C + + identifiers.

Identifier

A valid identifier is a sequence combination of one or more letters, numbers, or underscore characters (_). Spaces, punctuation marks, and symbols cannot be part of an identifier. In addition, identifiers must always start with a single letter. They also have the following underscore character (_), but such identifiers, in most cases, are left to compiler-specific keywords or external identifiers, and any identifiers that contain two consecutive underscore characters. In any case, they can start with a number.

A large number of keywords are used in C + + to help identify operations and data descriptions, so programmers cannot create variables with the same name as these identifiers. Standard reserved keywords that cannot be used for programmer-created identifiers are:

Alignas, Alignof, and, And_eq, ASM, Auto, Bitand, Bitor, bool, break, case, catch, Char, char16_t, char32_t, class, Compl, Const, CONSTEXPR, const_cast, continue, Decltype, default, delete, do, double, dynamic_cast, else, enum, explicit, export , extern, false, float, for, friend, Goto, if, inline, int., long, mutable, namespace, new, noexcept, not, Not_eq, nullptr, operator, or, or_eq, private, protected, public, register, reinterpret_cast, return, short, signed, sizeof, Static, Stati C_assert, static_cast, struct, switch, template, this, thread_local, throw, True, try, typedef, TYPEID, TypeName, Union, U nsigned, using, virtual, void, volatile, wchar_t, while, XOR, Xor_eq

Specific compilers may also have additional specific reserved keywords.

very Important : the C + + language is a "sensitive" language. This means that an identifier written in uppercase is not equal to another identifier of the same name that is written in lowercase letters. So, for example, the variable result is different from the result of the variable and the result of the variable. This is a three different identifier representing three different variables.

Basic data types

The value of a variable is stored in a location in computer memory in the form of 0 or 1. Our program does not need to know exactly where a variable is stored, it can be represented by its name. What the program needs to know is the data type of the variable when it is stored. Storing a simple integer and storing one letter or a larger floating-point number requires a different amount of memory, even though they are stored in the computer in 0 or 1, but they are interpreted differently in the program, and in many cases they occupy different memory.

The basic data type is the type of language implementation that most systems natively support for basic storage units. They can mainly be divided into:

(1) Character types: they are represented by a character, such as "a" or "$". The most basic type is char, which is a byte character. Of course, other types of characters are also available for wider use.
(2) Numeric integer types: They can store integer values, such as 7 or 1024, and they account for different sizes of memory and also depend on whether they have negative values or are signed or unsigned.
(3) floating-point types: They can represent a tangible value, such as 3.14 or 0.01, and the difference in floating-point types represents different levels of accuracy.
(4) Boolean type: Boolean type, in C + + called Boolean (bool), only two states, true (true) or False (false);

The Basic Data type table for C + + is as follows:

The names of some integer types can be expressed in a short notation with no signed or int, and only some parts of the above figure are not italicized and must be identified, and the italic part is optional. That is, the signed short int can be abbreviated as signed Short,short int, or a simple shorter; they all represent the same basic type.

In each of these types, the difference between the categories is only their size (that is, how much they occupy in memory), the first type in each group takes up memory is the smallest, and the last is the largest, each type is at least later than the same group of the front. In addition, the types in a group have the same other properties.

In the table above, except for the character (the exact size of a byte), no basic type has a standard size (but at least one minimum size). Therefore, types are sometimes unnecessary (in many cases) because there is a minimum size limit. This does not mean that these types are a type of indeterminate size, except that in different compilers and machines there is no uniform standard, and each compiler may specify the size of these programs in the running data type according to its own schema. This generalized size specification allows the C + + language to be flexible enough to adapt to the current and future optimization of various platforms.

The size of each type is defined as follows, the larger the range of numbers represented, the more memory is needed accordingly;

For integer types, the more values they represent, the greater the number they can represent; for example, a 16-bit unsigned integer can represent 65536 different values in the range 0 to 65535, and its signed value can in most cases represent a value between 32768 and 32767. Note that the range of positive values is signed when compared to the unsigned type's value. Because it is a 16-bit representation of a signed number, this is a data type that can represent a range of relatively large differences on the basis of a fully symbolic type.

For floating-point types, their size affects their precision, explicitly by the number of bits they have.

If the size or precision of a type that needs to be represented is not required, then char,int or some common integer, floating-point type can be represented. Other types in each type are used only in very special cases.

In the basic type of a particular system, the performance of the compiler implementation can be obtained by using the numeric_limits level (see Standard library). If, for some reason, a specific size type is required, the standard library defines a certain fixed-size type alias header.

The above types (characters,integers, floating-point numbers, and Boolean values) are known as the data types of the arithmetic type. But there are two other types of underlying types that exist, void, which represents a lack of identity type; nullptr, which is a special type of pointer. These types will be discussed in subsequent chapters on pointers.

C + + supports a variety of basic types based on the above, which are referred to as composite data types, which is the main advantage of the C + + language. We will also see more details in the future chapters.

Declaration of a variable:

C + + is a hard language, and requires each variable to declare its type before it is used for the first time. This allows the compiler to preserve the size of the variable in memory and how to interpret its value. In C + + syntax to declare a new variable is simple: We write only the type with the variable name (that is, its identifier). For example:

int a;float mynumber;

The above declares two valid variable types, the first declares an int type variable A, and the second declares a float of type mynumber. Once declared, the two variables can be used in other programs later.
If you want to declare multiple variables of the same type, you can declare them in a statement by using a comma-delimited identifier. For example:

int a, b, c;

Declare 3 variables A, B, C, they are of the same type, the following is the same as the above effect:

int a;int b;int c;

To see how variable declarations are in a program, let's take a look at the example of a C + + code at the beginning of the article:

//operating with variables  Span class= "Hljs-preprocessor" > #include <iostream>  using  namespace  STD ; int  Main () {//declaring variables:  int  A, B;  int  result;  //process:  a = 5 ;  b = 2 ;  A = a + 1 ;  result = A-B;  //print out the result:   cout  << result;  //terminate the program:  return  0 ;}  

Don't worry, if the other variable declarations look a bit odd, most of them will be explained in more detail in future chapters.

Initialization of variables:

When the above variables are declared, they have an indeterminate value until they are assigned a value. However, it may have a specific value at the time it is declared, which is called the initialization of the variable.

In C + +, there are three ways to initialize a variable. In the course of many years of evolution, they are all equal;
The first, called Class C initialization (since it is inherited from the C language), includes a variable that adds a value after an equal sign to initialize:

typeidentifier

For example, declaring an x variable of type int, initialized to zero, we can write:

int x = 0;

Another method, called the initialization of the constructor (which describes the C + + language), is initialized in parentheses (()), such as:

int x (0);

Finally, the third method, called unified initialization, is similar to the above, but uses curly braces ({}) instead of parentheses (this is described by the C + + standard, revision 2011), such as:

int x {0};

One of the above three types of programs:

//Initialization of variables#include <iostream>using namespace STD;intMain () {intA=5;//Initial value:5  intb3);//Initial value:3  intc{2};//Initial value:2  intResult//Initial value undeterminedA = a + B; result = A-c;cout<< result;return 0;}
Type inference: Auto and Decltype

When a new variable is initialized, the compiler can automatically give the type of the variable by initialization, at which point the type of the variable can be defined using the auto identifier:

int0;auto bar = foo;  // the same as: int bar = foo;

Here, the variable bar is declared to have an auto type; so the type of bar is the type of the value that initializes it: in this case it uses the type foo, which is int.

Variables that are not initialized can also be pushed indirectly to the type of the variable using the decltype specifier:

int0;decltype(foo) bar;  // the same as: int bar;

Here, bar is declared as having the same type as Foo.

Auto and Decltype are powerful features recently added to the C + + language. However, the use of type deduction is generally used when the type cannot be determined or used to improve the readability of the code. The above two examples do not use these two functions. In fact, they may degrade readability because, when reading the code, it is necessary to find the type of foo that corresponds to bar.

Introduction to Strings:

The basic type is the most basic type that computer code can run. But the main advantage of the C + + language is its rich composite type, which makes up the cornerstone of Modularization.

One example of a composite is the string class. Variables of this type can store character sequences, such as words or sentences, which is a very useful feature in C + +!

One difference in the basic data types is to declare and use objects (variables) of this type, and the program needs to include the header file (header file < string >) of the standard library where this type resides:

// my first string#include <iostream>#include <string>usingnamespacestd;int main (){  string mystring;  "This is a string";  cout << mystring;  return0;}

As you can see from the previous example, string initialization can be any valid string, just as a variable of a numeric type can be initialized to any valid numeric value. With the base type, all of the following initialization formats are valid string initializations:

string"This is a string";string mystring ("This is a string");string mystring {"This is a string"};

Strings can also perform basic operations on all basic data types, such as the ability to not be initialized, or to change their values during execution:

// my first string#include <iostream>#include <string>usingnamespacestd;int main (){  string mystring;  "This is the initial string content";  cout << mystring << endl;  "This is a different string content";  cout << mystring << endl;  return0;}

Note: Inserting Endl is an end-of-line operation (printing a newline character and an output stream).

The string class is a compound type. As you can see in the example above, a composite type is used to declare a variable and initialize the same way as the base type.

For more details on standard C + + strings, see the description of the string class.

C + + Tutorials (iii: Variables and Types)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.