Hello, C + + (7) Part III definition and initialization of 3.2.1 variables in C + + world sentient beings

Source: Internet
Author: User
Tags readable truncated

Part 3

C ++ world beings

After listening to HelloWorld.exe's self-introduction and completing the first close contact with the C ++ world, are you all eager to try your hand and start writing C ++ programs? The two main tasks of the program are describing data and processing data. So, the first question we will face next is: how to describe data in C ++?

3.1 Data types in C ++
Programming is the use of programming languages to describe and express the real world. There are many objective things in the real world, such as computers, people, cars, and so on. We always use various data to describe the different attributes of these things. For example, we use a string "ChenLiangqiao" to describe a person's name; a number "175" to describe his height. Some of these data can often be attributed to the same type. For example, the data describing the height of a person and the screen size of a computer are both numeric data, while the data describing a person's name and car license plate are both string data. Correspondingly, in C ++, in order to describe these data, we abstract the same type of data into a certain data type, and then use variables defined by this data type to express this kind of data. For example, we abstract various integers in the real world (175 for height and 21 for screen size) into the data type int in C ++, and then use variables defined by int to describe a specific integer data. For example, we can define an int variable nHeight to indicate the height of a person; define another int variable nSize to indicate the size of a TV.

Here we can also see that the same data type (int) can define multiple different variables (nHeight, nSize), which are used to represent multiple different specific things (height, size). Conversely, multiple variables (nHeight, nSize) representing different things can also be the same data type (int). This is like a hundred surnames in the real world. There can be many people (nHeight, nSize) with the surname Chen (int), and many people (nHeight, nSize) can also have the surname Chen (int). The data type of a data determines which person this data belongs to, and since it is the same person, then the family has some of the same characteristics. For example, they all occupy the same number of bytes of memory, they can all represent the same range of data, and so on. As shown in 3-1.

In C ++, according to the complexity of the data that can be expressed, data types can be divided into basic data types and structured data types.

Basic data type
There are many simple data in the real world, such as a number, a character, and so on. In order to express these simple data, C ++ abstracts these data into various basic data types. For example, 175 representing the height of the person and 21 representing the size of the TV are integers. C ++ abstracts these integers into the int data type; A, B, C, and D representing multiple choice options are all characters, and C ++ abstracts the characters into char type of data. Basic data types are the most basic data types in C ++. They are the lowest-level people in the C ++ world. They all have self-explanatory characteristics and are no longer separable.

2. Constructing data types
The real world is complex, and using only the basic data types provided by C ++ cannot fully describe the complex real world. For example, we cannot describe a rectangle with data of a basic data type, because a rectangle has two properties, length and width, that need to be described. However, we found that complex things are composed of simple things. A complex thing can be broken down into multiple simple things, and combining multiple simple things also constitutes a complex thing. Corresponding to the real world, C ++ also provides a combination of structures and classes, which can combine multiple basic data types to form a more complex structured data type to describe more complex things. For example, you can combine two simple basic data types int to form a new data type Rect, which is used to describe more complex rectangles. In C ++, you can use the struct keyword to create a new constructed data type:

// Create a data structure Rect describing the rectangle
struct Rect
{
    int m_nLength; // represents the length of the rectangle
    int m_nWidth; // represents the width of the rectangle
};

// Use Rect to construct a data type to define a variable r that represents a rectangle
Rect r;
r.nLength = 4; // make the rectangle length 4
r.nWidth = 3; // make the width of the rectangle 3
A constructed data type can be broken down into "members" or "elements". Each "member" is either a primitive data type or another constructed data type. If we consider the basic data types as atoms in chemistry, then the construction data types can be regarded as molecules (Rect) composed of atoms (int). According to the combination form, the structured data types in C ++ can be divided into 4 types: ① array type; ② structure type; ③ union type; ④ enumeration type. These construction data types are described in detail in later chapters.

3.2 Variables and constants
The C ++ world is full of various data volumes. Essentially, they are data stored in a memory location. Some of these data need to be changed while the program is running. For example, the data 175 representing a person's height may become 180 during the running of the program. At the same time, there is another type of data in the program, which remains unchanged during the entire program. For example, 3.14159, which represents the pi, will not change at any time during the program. We refer to the amount of data that may change during the running of the program as a variable, and the amount of data that is always the same is called a constant.

3.2.1 Definition and Initialization of Variables
In order to save the data, we first need to open a suitable memory space for it. At the same time, for the variables in the program, we often need to read and write them multiple times. To facilitate access to variables, we often need to give the variable a name, and then access the data it represents through the variable name. If we want to express a specific variable data in the real world, we can use the data type corresponding to this data to define a variable according to the following syntax:

Data type specifier variable name;
// define multiple variables of the same type at the same time
// Deprecated form, multiple variables are confusing and the code is not readable
Data type specifier variable name 1, variable name 2, variable name n;
A variable definition consists of a data type specifier and a variable name. The data type is a description of the variable type. It is used to specify whether the variable is an integer, floating point, or custom data type. Therefore, it also determines some basic characteristics of the variable, such as the number of bytes of memory occupied and the value Range, etc. A variable name is a symbol used to mark a variable, which is equivalent to the name of the variable. We can read and write the data represented by the variable through the variable name. For example, we want to represent a person's variable height data 175 in the program, and the data type of 175 is an integer, and the corresponding C ++ data type is int, so we choose int as the data type of the variable. And because this variable represents the height of a person, we choose nHeight (n represents this is an integer, Height represents this is the height data) as the variable name:

// Define a variable nHeight of type int to represent height
int nHeight;
After completing the definition of such a variable, it is equivalent to opening up 4 bytes of memory space for the 175 data to be saved (a variable of type int occupies 4 bytes of space in memory), and the name of this variable is specified as nHeight, and then you can save the 175 height data to memory or read and write access it through the variable name nHeight:

// write data through nHeight
// Save the height data of 175 to memory
nHeight = 175;
// read data through nHeight
// Display height data 175 represented by nHeight variable to the screen
cout << "Height:" << nHeight << endl;
// Modify height data to 180 by variable name
nHeight = 180;
// Output the modified height data
cout << "Modified height:" << nHeight << endl;
When defining variables, note the following.

l You cannot use C ++ keywords as variable names. For example, common keywords such as bool, for, do, and case (shown as special colors such as blue in the IDE) cannot be used as variable names; variable names cannot begin with numbers. For example, the following variable definitions are all incorrect:

int case; // error: case is a keyword
int 2member; // error: variable name starts with a number
Know more: How many keywords are there in C ++?

Keywords (keywords), also known as reserved words, are identifiers pre-reserved by C ++ throughout the language. Each C ++ keyword has a special meaning to accomplish a specific function. For example, int means integer data type; for means to define a loop statement; class means to define a class and so on. Because keywords have predefined meanings, they cannot be used as identifiers (variable names, function names, class names, etc.). The keywords of C ++ are shown in the table below.

Table 3-1 Keywords in C ++

  alignas (enabled in C ++ 11)
  alignof (enabled in C ++ 11)
  and
  and_eq
  asm
  auto
  bitand
  bitor
  bool
  break
  case
  catch
  char
  char16_t (enabled in C ++ 11)
  char32_t (enabled in C ++ 11)
  class
  compl
  const
  constexpr (enabled in C ++ 11)
  const_cast
  continue
  decltype (enabled in C ++ 11)
  default
  delete
  do
  double
  dynamic_cast
  else

  enum
  explicit
  export
  extern
  false
  float

for
  friend
  goto
  if
  inline
  int
  long
  mutable
  namespace

new
  noexcept (enabled in C ++ 11)
  not
  not_eq
  nullptr (enabled in C ++ 11)
  operator
  or
  or_eq
  private
  protected
  public
  register
  reinterpret_cast

  return
  short
  signed
  sizeof
  static
  static_assert (enabled in C ++ 11)
  static_cast
  struct
  switch
  template
  this
  thread_local (enabled in C ++ 11)
  throw
  true
  try
  typedef
  typeid
  typename
  union
  unsigned

using
  virtual
  void
  volatile
  wchar_t
  while
  xor
  xor_eq

Here is a list of all 84 keywords in C ++, but most of them are rarely used. We don't need to master all of these keywords. We only need to master one or twenty of the most commonly used ones. As for other keywords, you can check the information when you need it.

l Allow multiple variables of the same type to be defined simultaneously after a data type specifier. Separate variable names with commas (the commas must be English commas). E.g:

// define three variables of type int at the same time,
// Represent the student's ID (nStuID), age (nAge), and height (nHeight)
int nStuID, nAge, nHeight;
l There must be at least one space between the data type specifier and the variable name.

l The last variable name must end with ";" to indicate the end of the statement.

l The variable definition must be placed before the variable is used. In other words, variables must be defined before they are used.

Best practice: Variable definitions should be as close as possible to where the variables are used

We know that variables can only be used after they are defined, that is, variables must be defined before they can be used. So, to what extent is this "before" suitable? Is 1 line of "before" appropriate or 100 lines of code appropriate? In the face of this problem, we do not have a fixed standard answer, but we have a principle that should be followed: variable definitions should be as close as possible to where the variables are used.

If the location of the variable definition and the location where the variable is actually used are too far apart, many things can happen in between. For example, the program may quit halfway, the defined variables are not used and wasted; or it may be used incorrectly in the middle, causing problems that are difficult to find for the program. On the other hand, if the two are too far apart, when we use a variable, it is difficult to find the location where it is defined, so we cannot easily know the basic information such as the data type of the variable, which affects our use of the variable. So, in order to avoid these possible troubles, a simple and effective method is to delay the timing of variable definition as much as possible, as close as possible to the location where it is actually used.

When defining variables, in addition to determining the data type of the variable, another important task is to give the variable a good name. If a person has a good name,It's easy to make a good and impressive impression, and so are the names of the variables. Appropriate variable names contain variable-related information that can be self-explanatory, make it easier for people to understand and use, and improve the readability of the code. So how do you give a variable a proper name? Compare these four variable names:

// Variable that records the number of students
int nStuNum;
int N;
int theNumberofStudent;
int xssl;
These four variables are used to indicate the number of students. If you want to ask which of the four variable names is the best, everyone will definitely say that the first variable name is the best, because the first variable name is known at a glance to indicate the number of students. The others have their own shortcomings: the second one is too short to know the specific meaning of this variable; the third one is too long, which is cumbersome to write; the fourth one uses the acronyms of Hanyu Pinyin, which is even more impressive. Misty water.

A good variable name can properly explain the meaning of the variable. Without excessive comments or documentation, the entire code is clear and readable, and it can be "wish for meaning." To get a good name for a variable, you usually follow some naming convention. The more popular naming rule in the industry is the "Hungarian nomenclature" advocated by Microsoft. In Hungarian nomenclature, a variable name consists of three parts:

Variable name = property + type + object description

Among them, attributes are usually used to explain some additional information about this variable. For example, we usually use the "m_" prefix to indicate that this variable is a member variable of a class, and use the "g_" prefix to indicate that this is a global variable; the type indicates the data type of this variable, usually using the Abbreviated representations of these data types. For example, we usually use n for int and f for float. The object description is a description of the meaning of this variable. It is usually a noun. Combining these three parts constitutes a complete variable name, which can express a wealth of information about this variable. For example, the name of a variable is "m_unAge", and the meaning of the variable expression is known by looking at the variable name: this is a member variable (m_) of a class, its data type is unsigned int (un), and it It is used to describe the Age attribute of this class.

Learn more: Where did the "Hungary" in Hungarian nomenclature come from?

The Hungarian nomenclature was first proposed by a Hungarian programmer named Charles Simonyi, and he later worked for several years at Microsoft because this nomenclature provides a good summary of the most important information about variables with very few words. Recognized by Microsoft and gradually becoming popular within Microsoft. Because of Microsoft ’s strong influence in the industry, the Hungarian nomenclature has also begun to spread to the world through Microsoft's various products and documents, and it has gradually become the most popular variable naming method in the industry. For most programmers, this variable nomenclature is used more or less no matter what development language they use.

This nomenclature is called "Hungarian nomenclature" in honor of the country from which the inventor came.

Using Hungarian nomenclature, you can express rich information in a variable name, which improves the readability of the code to a certain extent. But it also has one of the biggest drawbacks-tedious. Sometimes, too long and meaningless prefixes add extra burden to variable names. This is why it is not used by all programmers worldwide. There is no such thing as the best naming rule in the world. In practice, a naming rule that is satisfactory to most project members can be formulated according to some common rules popular in the industry, combined with the actual situation of the project, and implemented in the project. The "best" rule is the "best" rule. After practical tests, some common naming rules popular in the industry are as follows.

Easy to understand
The variable names should be intuitive and easy to spell, and they should be textual. Variable names are best to use English words or combinations for easy memorization and reading. Do not use Chinese Pinyin to name, because such variable names can only be understood by you. English words in the program should not be too complicated. Be authentic and accurate. For example, naming a variable representing "current value" as "fNowVal", although it can express the meaning of the variable, it is far from "fCurVal".

2. The shortest length, the largest amount of information
Generally, the compiler has no limit on the length of variable names. Generally speaking, long names can better express the meaning of variables, so it is not surprising that variable names in C ++ are as long as a dozen characters. Since there are no restrictions, isn't the longer the name of the variable the better? not necessarily. As long as the meaning of the variable can be fully expressed, the simpler the variable name, the better. For example, to indicate the maximum value, the variable name "max" is more useful than "maxValueUntilOverflow" because it expresses the largest amount of information with the shortest length.

3. The larger the scope, the longer the variable name
Regarding the length of variable names, we can also remember such a simple rule: the length of a variable name (or the function name to be described later) is positively related to its scope size. The so-called scope is the range of code in which an identifier (variable name or function name) takes effect. For details, refer to the following section 7.3.3. In other words, if the scope of a variable is relatively large, then there will be more variables in this scope. In order to avoid conflicts and facilitate distinguishing, the variable name should be relatively long. vice versa. For example, inside a function, we can use a simple i to name a local variable, and in the global scope, it is not appropriate to use i to name a global variable.

4. Variable names consist of nouns
A variable represents a specific thing in the real world, and its essence is a data entity, so the core of a variable name should be a noun, so it should use a single "noun" or "adjective + noun" combination. E.g:

float fWeight; // noun, which means someone's weight
float fLastWeight; // adjective + noun, last weight
float fCurWeight; // adjective + noun, indicating the current weight
4. Don't use numeric numbers

Try to avoid numerical numbers in variable names, such as "Value1", "Value2", etc., unless numbering is really needed logically.

5. Constant capitalization
Constants are special variables of a certain type, and their speciality lies in that they cannot be modified. This particularity is reflected in the naming, that is, we usually use uppercase letters to represent variable names, and if there are multiple words in the constant name, they are separated by underscores. E.g:

const float PI = 3.14159; // define a constant PI of type float with the const keyword
const int MAX_LEN = 1024; // split constant names with underscores
6. Use conventional prefixes

Some conventional variable name prefixes can explain some attributes of variables well and make the meaning of variables clear at a glance. For example: the variable prefixed with s_ means a static variable; the variable prefixed with g_ means a global variable; the variable prefixed with m_ means a member variable.

After the definition of the variable is completed, the system will allocate memory space for this variable, and then we can read and write access to this memory by the variable name, save data to or read data from memory. However, before we actually use a variable, we often need to properly initialize it. This is because after the variable is defined, if it is not initialized, the system will give an uncertain random value as its initial value. This random value may vary depending on the compiler and target platform. This may lead to inconsistent behavior of the same program on different platforms, leading to migration issues. At the same time, if you accidentally use this random value for operation, it may cause the program to run incorrectly or even crash the program, which is a disaster. Variable initialization will give the variables a reasonable initial value, which can avoid these problems well. Therefore, at the beginning of learning C ++, you should develop a good habit of "initializing variables while defining them."

So how do we initialize variables?

The first way, you can use the "=" assignor to assign a suitable initial value to this variable while defining the variable. E.g:

// Define a variable nHeight of type int, and initialize its value to 175 using "="
int nHeight = 175;
The second way is to use "()" to give the initial value after the variable name when defining the variable. The system will use this initial value to complete the creation of the variable and complete the initialization. E.g:

// initialize its value to 175 by "()"
int nHeight (175);
In addition to the above two methods, in the C ++ 11 standard, we can also use a pair of braces "{}" to initialize the list (initializer list) to complete the initialization of variables when defining variables. E.g:

// Initialize its value to 175 through the initialization list
int nHeight {175};
Best practice: Why use an initialization list?

At this point, everyone naturally asks this question: "=" and "()" can be used to initialize variables in C ++. Why use an initialization list to initialize variables?

The initialization list is a new feature introduced in the C ++ 11 standard. In addition to the form of unified variable initialization, it also brings another benefit: it can prevent the truncation of the data type when the variable is initialized, and prevent the loss of data accuracy. The so-called data type truncation, in short, is the use of data of a higher precision data type (for example, double) to assign a variable of another lower precision data type (for example, int), C ++ will perform implicit type truncation to meet the needs of type conversion. E.g:

int x = 7.3; // a double data 7.3 is truncated to an int data 7
When compiling the above code, although the 0.3 data was lost in the process, the compiler will not give any error or warning message. However, in C ++ 11, if the initialization list "{}" is used for initialization, the compiler will warn about the truncation of this data type, prompting the user to lose the accuracy of the data. E.g:

// Warning: Initializing a variable of type int with data of type double will result in type truncation and loss of data precision
int x1 = {7.3};

// Correct: Although 7 is an int type data, it can be accurately expressed using the char type,
// thus not cause truncation of data types and loss of precision errors
char x2 {7};
In C ++, if an initial value can be accurately expressed as the target type, there is no data type truncation. Note, however, that conversions from double to int are generally considered to be truncated data types, resulting in a loss of precision, even when converting from 7.0 to 7. The processing of the initialization list for type conversion enhances the security of the C ++ static type system. Traditionally, it depends on the programmer's initialization type safety check. In C ++ 11, the initialization list is implemented by the compiler, which will reduce the programmer's burden and be more secure. So, if possible, you should use the initialization list whenever possible to complete the initialization of variables.

It is important to point out here that we cannot use an initialization list for the auto type (a special data type, which is equivalent to a placeholder for a data type. When using it as a data type to define a variable, it is not specifically specified The data type of the variable, the actual data type of the variable will be automatically inferred from its initial value at compile time. In the later section 3.5.2, we will introduce it in detail). In that case, the type of this variable will be detected by the compiler as the type of the initialization list, rather than the type of the true initial value in the initialization list.

Learn more: User-defined literals create special data

When representing data, C ++ provides many built-in data type data identifiers for us to use. In this way, when we express data, adding the corresponding data identifier will make the data we want to express more accurate and intuitive. E.g:

1.2 // default double double precision floating point
1.2F // F specifies a float single-precision floating-point type
19821003ULL // ULL means unsigned long long 64-bit unsigned long
In addition to these built-in data identifiers, C ++ 11 also supports user-defined data identifiers by adding a user-defined suffix to the variable to support the "user-defined data identifier", for example:

// define the data identifier inch
constexpr double operator "" _inch (const long double in)
{
    return in * 0.0254; // convert inches to meters
}
Here, we actually define an operator (must start with "_"), which takes the data before the operator as a parameter, and the parameter type is the type with the largest range of corresponding data values. For example, an integer is an unsigned long long, and a floating-point number is a long double. Of course, the entire data can also be passed as a string as a const char * parameter. After a certain processing of the incoming parameters, the real data represented by this data plus the data identifier is returned. In this way, we can use the user-defined data identifier "_inch" directly in the program to directly define the data in inches. E.g:

// Define the size of a TV as 54 inches,
// Then convert the data in meters to the variable tvsize
double tvsize = 54.0_inch;
cout << "54 inch =" << tvsize << "m" << endl;
In the above code In, we use the "_inch" data identifier to directly define the size of the TV. When the compiler compiles this code, it first analyzes the suffix of the data assigned to the variable, then uses the data before the suffix as a parameter, calls the function that defines the data identifier, and uses the return value of the function as the real value of this data. The user-defined data identification mechanism simply allows the user to formulate a new suffix and decide how to process the data before it. Among them, we can convert units, such as converting inches to meters, or construct new data types, such as constructing a binary number to a decimal number, and so on.

Because we use the constexpr keyword when defining the data identifier, the role of the constexpr keyword is to perform preprocessing calculations at compile time, so when compiling, the compiler will directly convert this data in inches to The data are measured in meters and assigned to the corresponding variables.

In this way, we can directly represent various types of data in the code, such as inch length, angle, binary number, etc., making us more intuitive, convenient and humane when using different types of data Into.

 

Original address: http://www.cnblogs.com/nihaoCPP/p/3966286.html

(Reproduced) Hello, C ++ (7) Part III C ++ world beings 3.2.1 Definition and initialization of variables

Related Article

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.