C++primer second chapter variables and basic types

Source: Internet
Author: User
Tags pow

A type is the basis of a program. The type tells us what the data represents and can perform those actions on the data.

Several types of C + + language definitions:

    • Character type
    • Integral type
    • Floating point Type

also supports custom data types

Data types determine the meaning of data and operations in a program

I=i+j;

    • int:5=2+3;
    • String:hello World = Hello + world;

2.1. Basic built-in type

Calculation: integer or float type used to store numeric values

Statement Description: String or type of string store statement

Judging condition: BOOL Type store truth

2.1.2. Integral type

Integer, character, and Boolean arithmetic types are synthesized as integers. Relative to floating-point type.

Character type: char and wchar_t.

Integers: short, int, and long differ: the size of the storage space is different. The use is not the same

Machine-level representations of built-in types

C + + built-in types are closely related to how they are represented in memory in your computer. The computer is stored as a bit sequence, with each bit 0 or 1.

  

For example, the byte corresponds to the address

Signed and unsigned types

In addition to the bool type, the type can be signed (signed) or unsigned (unsigned).

Representation of an integer value

In unsigned form, all bits represent numeric values. Like unsigned says 0~255

Signed, one of them as a sign bit, -128~127

Assignment of integral type

The compiler assigns values after the values that do not correspond to the relationship are modulo.

unsigned char 0~255

Assign a value of 256 to unsigned char

Assigns a value of 1 to unsigned char

2.1.2. Floating-point type

Type float, double, and long double single-precision, dual-precision, and extended-precision floating-point numbers

Float:6 bit valid number

Double:10 bit valid number

2.2. Literal constants

42, 3.1415926 the number of fixed value is a literal constant

Only built-in types have literal constants

    • Decimal
    • Octal 0 Start
    • Hex 0x Start

  Literal constant Rule : can be modified after the value, such as 3.14f. 001f 12.345L 3.1415e0f

Floating-point literals constant (not decorated) default to double type

  Boolean literals and character literals

True and False are Boolean literals

' A ' ' 2 ' ... Is the character literal note differs from the 1 2 3 integral type

  Escape sequences for nonprinting characters

  

String literals

"Hello World"

Note the difference between "a" and ' a ': "A" is a string, and the string consists not only of a single character, but a special marker, which marks the end of the string.

' A ' is just a simple character

Connection of string literals

1 " a multi-line " 2             " string literal " 3             " using concatenation " 4          << Std::endl;

This statement outputs: a mutitude-line string literal using concatenation

1 " multi-line " " literal " << Std::endl;

This is undefined and the output is not necessarily

Multi-line literals

Add a backslash to the end of a line to treat this line and the next line as the same line.

1 Std::cou 2 t<<"" << St3 D::endl;

Note: The backslash symbol must be the trailing character of the line----No comments or spaces are allowed.

  Variable

Calculate 2^10

1#include <iostream>2 intMain ()3 {4Std::cout <<"2 raised to the power of:";5Std::cout <<2*2*2*2*2*2*2*2*2*2;6Std::cout <<Std::endl;7        return 0; 8}

What if we calculate 2^30?

#include <iostream>intMain () {intValue =2; intPOW =Ten; intresult =1;  for(intCNT =0; CNT! = pow;++CNT) {Std::cout<< value <<"raised to the power of"<< POW <<": \ t"<<result <<Std::endl;
}
return 0;}

2.3.1. What is a variable

A variable provides a named store that the program can manipulate. Each variable has a specific type.

Expressions are divided into: left and right values

Lvalue: The left or right of an assignment statement.

Right value: can only appear to the right of the assignment.

2.3.2. Variable name

Variable names, which are identifiers of variables, can consist of letters, numbers, and underscores.

Must start with a letter or underscore and be case-sensitive

The habit of variable names:

    • Variable names are usually in lowercase letters
    • Identifiers should be used to help remember the name
    • Identifiers that contain multiple words add an underscore between each word or capitalize the first letter of each word.

2.3.3. Defining objects

1 int Unit_sold; 2 3 Double Sales_price,avg_price; 4 5 std::string  title; 6 7 Sales_item Curr_book;      

Each definition starts with a type specifier followed by a comma-separated list of specifiers or descriptors. The semicolon ends.

Initialization

Two forms: Copy initialization and direct initialization

int ival (1024x768);    Direct initialization of int1024x768;   Replication initialization

2.3.4. Variable initialization rules

When a defined variable is not initialized, the system sometimes helps us initialize, depending on the type of the variable and the position of the variable.

Initialization of built-in type variables

Depends on the location.

Variables defined outside the body of the function are initialized to 0, and variables defined inside the function body are not initialized.

Initialization of class-type variables

Each class defines how an object of that class can be initialized. class controls the initialization of class objects by defining one or more constructors.

If you define a variable of a class without providing an initialization, the class can also be initialized with the default constructor.

2.3.5. Declarations and definitions

The definition of a variable is used to allocate storage space for a variable, and you can specify an initial value for the variable.

A declaration is used to indicate to a program the type and name of a variable.

2.3.6. Scope of the name

In a C + + program, each name is associated with a unique entity. Most scopes are defined with curly braces.

1#include <iosteram>2 intMain ()3 {4     intsum =0;5      for(intval =1; Val <=Ten;++val)6sum+=Val;7Std::cout <<"Sum of 1 to ten inclusive is"8<< sum <<Std::endl;9     return 0;Ten}

Global scope: Defines names outside of all functions

Local scope: defined inside or within parentheses.

Scoped in C + + can be nested

#include <iostream>#include<string>/*Program for illustration purposes only:* It's bad style for a function to use a global variable and then* define a L Ocal variable with the same name*/std::stringS1 ="Hello";//S1 has global scopeintMain () {std::stringS2 =" World";//S2 has local scope//uses global s1; prints "Hello World"Std::cout << S1 <<" "<< S2 <<Std::endl;intS1 = the;//S1 is local and hides global S1//uses local s1;prints "World"Std::cout << S1 <<" "<< S2 <<Std::endl;return 0;}

2.3.7. Defining a variable at the point where the variable is used
In general, the definition or declaration of a variable can be placed anywhere in the program where the statement can be placed. Variables must be declared or defined before they are used.
It is usually a good idea to define an object in the place where it was first used.

2.4. Const qualifier

 for (int0, + +index) {//  ...}

After improvement

int  + // Input buffer size  for (int0; Index! = bufSize; + +index) {//  ...}

There is still a serious problem with the method of defining a variable to represent a constant. That is, bufSize can be modified. BufSize may be intentionally or unintentionally modified. The Const qualifier provides a workaround that transforms an object into a constant.
const int bufSize = 512; Input buffer size

2.5. References

A reference is another name for the object. In a real program, a reference is used primarily as a formal parameter to a function.

int 1024x768 ; int // Ok:refval refers to Ival int // error:a Reference must be initialized int Ten // Error:initializer must is an object

2.6. typedef name

typedef can be used to define synonyms for a type:

Double // wages is a synonym for double int // Exam_score is a synonym for int // indirect synonym for double

typedef is commonly used for the following three purposes:
• To hide a specific type of implementation, emphasize the purpose of the use type.
• Simplify complex type definitions to make them easier to understand.
• Allows a type to be used for multiple purposes, while making clear the purpose of each use of the type

  

2.7. Enumeration

we often need to define a set of selectable values for some properties. For example, there may be three types of file open : input, output, and append. One way to record these status values is to have each state associated with a unique constant value. We might write code like this:

const int input = 0;
const int output = 1;
const int append = 2;
While this approach works, it has an obvious drawback: it does not indicate that these values are associated. Enumerations provide an alternative way to define not only the set of integer constants, but also the aggregation of them into groups.

Defining and initializing enumerations

  

// input is 0, output was 1, and append is 2 enum open_modes {input, output, append};

2.8. Class type

2.9. Write your own header file

The generic class definition is placed in the header file. To allow the program to be separated into separate logical blocks, C + + supports the so-called separate compilation. This program can consist of multiple files

2.9.1. Designing your own header files

Header files typically contain the definition of a class, the declaration of an extern variable, and the declaration of a function

The correct use of the header file can bring two benefits: Ensure that all files use the same declaration of the given entity, and that only the header file needs to be updated when the declaration needs to be modified.

  Header files are used to declare rather than to define

    Because header files are contained in multiple source files, they should not contain definitions of variables or functions.

2.9.2. A brief introduction to the preprocessor

Avoid multiple inclusions

#ifndef Salesitem_h #define Salesitem_h//  Definition of Sales_itemclass and related functions goeshere#endif

Using a custom header file

  

#include instructions are accepted in the following two forms:
#include <standard_header>
#include "my_file.h"
If the header filename is enclosed in angle brackets (< >), the header file is considered a standard header file. The compiler will look for the header file in a predefined set of locations that can be modified by setting the Find PATH environment variable or by using a command-line option. The lookup methods used vary widely depending on the compiler. If the header file name is enclosed in a pair of quotes, then it is considered a non-system header file, and the lookup of the non-system header file usually starts at the path where the source file resides.

C++primer second chapter variables and basic types

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.