Chapter 8 Basic Overview
This chapter is intended to explain some concepts that understand C vital, and C programmers will be very familiar with many of these concepts, but there are some subtle differences that may result in unexpected procedures, including the following processes:
* the term
* Description and definition
* Range
* Program and connection
* Start and end
* Storage class
* Types of
Additional topics include l-value, R value, and numerical range boundaries.
the term
The C terminology used in this book gives the definition in Table 2.1:
Table 2.1 C terminology
Terminology The term explanation describes the names and their types to a program, without having to define associated objects or functions. However, there are many instructions that are defined as definition definitions, which allows the compiler to assign a memory or a function of generating a code for a function to generate a code life. It is an object presence or absence of a time-to-segment connection name that can be created and destructure. Or there is no connection, in one program (a set of conversion units), only the name with an external connection represents the same object or function. In a conversion unit, names with internal or external connections can represent the same object or function (except when the function is overloaded). (For more information on the conversion unit, see "Translation Phase" in the "Preprocessor Reference" after this book. The unconnected name only means that the unique object or function name name represents an object, function, overloaded function set, enumeration element, type, class member, template, value or label, C program name points to them related to them Language elements. Name can be a type name or identifier object an object is an instance of a user-defined type (a class type). The difference between an object and a variable is the variable retention status information, and the object can also have actions. The difference between the objects and variables given in this manual is: "Object" refers to an instance of the user-defined type, and "variable" refers to an instance of the basic type. In the case of object or variables, the term "object" is used as an inclusive term, meaning "object or variable" range, only within a particular area of the program context, these areas are called name storage classes The stored class of the named object refers to its survival period, initialization, and a certain name of its connection type with related types. It is a variable that stores the value stored in an object or by a function. A basic type (such as int, float or double) data item, variable storage status information but does not define actions for information. See "Object" items listed above to get the term "variable" and "objects" are used in this document.
Description and definition
Description Tell the compiler A program element or name existence, define what code or data describes the specified name, and a name must be used first.
Understand
An explanation introduces one or more names into a program, which illustrates more than once in one program, and therefore, the class, structure, enumeration type, and other user-defined types can be explained for each compilation unit. Many illustrative limits are all descriptions must be identified. The description can also be used as a definition, except for the following description:
> Is a function prototype (no function of function)
> Have extern indicators but no initial expressions (objects and variables) or function (functions), which means that this definition is not required in the current conversion unit and gives an external connection.
> Is a static data member inside the class.
Since static class data is shared by all members of the class, they must define and initialize the outside of the class description (see Chapter 8 "Class" for more information on classes and class members).
> Is a class name description without definition, such as Class T;
> Is a TypeDef statement
Description is also an example of definition:
// Describe and define integer variables I and J
INT i; int J = 10;
// Description Enumerate Suits
ENUM Suits {spades = 1, clubs, hearts, diamonds};
// Description Class Checkbox
Class Checkbox: public control {public: boolean ischecked (); virtual int changeteate () = 0;}
Some explanations are not definitions:
Extern INT I;
Char * strchr (const char * str, const char target);
Definition
One definition is a unique specification for objects or variables, functions, classes, or enumerations, because the definition must be unique, so a program can only contain one definition for a given program element.
The description and definition can be multi-one relationship. There are two cases in one program element to be explained, but not defined: * The function is described but never uses a function call or a expression of the function address.
* A class is only used for the case where it is not required, however, the class must be explained, the following code describes this:
Class windowCounter; // forward reference, no definition
Class window {static windowcounter windowcounter; // WINDOWCOUNTER definition is not required}
Fan
The name of C can only be used for a specific area of a program, and this area is called a "range" of the name. The range determines that a survival period of the name of the object does not represent a static range, and the scope also points to see the visibility of a name when the class constructor is called, and the part of the local variable is initialized. (See Chapter 11 "Construction" and "Destructure" section in the "Special Member Function").
There are five ways:
> Local range, the name of the description in one block is only in this block and is accessible within the block included in this block, and only starts from the description. A function has a local scope in the name of the ordinary parameters within the outermost block range of the function, as if they are described in the block containing the function body, consider the following code segments:
{INT I;
Since i's instructions are included in the block enclosed in the parentheses, I has a partial range and never be accessed because there is no code to access the operation before closing the brackets.
> Function range, the label is the only name with a function range, which can be used anywhere in a function, but cannot be accessed outside of the function.
> File range, any name of the external description of all blocks or classes has a file range, and after its description, any location of the conversion unit is accessible. The name of the file range does not indicate the name of the static object is often referred to as "global" text.
> Class range, class member name has a class range. The class member function can only use the member selection operator (. * Or ->) or member pointer operator (. * Or -> *) or pointing to the pointer to the object of the class, non-static member data is considered Objects relative to that class are topical.
Consider the following description:
Class Point {INT X; Int Y;
Class members X and Y are considered to be within the class Point.
> Prototype range, the name illustrated in the function prototype is only visible to the end of the prototype. The following prototypes illustrate two names (szdest, szsource); these names are out of range at the end of the prototype: char * STRCPY
(char * szdest, const char * szsource);
Instruction point
A name is considered to immediately explain it before it (optional) initializes after its specifier. (For more information on the specifier, see Chapter 7 "Settings"). An enumerator is considered to be immediately explained after named its identifier, but immediately before it is initialized.
Consider this example:
Double dvar = 7.0; void main () {double dvar = dvar;}
If the description point is initialized, the local DVAR will be initialized to 7.0, that is, the value of the global variable DVAR. However, this is not the case, so DVAR is initialized to an undefined value.
Enumerates the same rule, but the enumerator is output to the enumeration range. In the following example, an element Spades, Clubs, Hearts, and Diamonds are explained, because the enumerator is output to the closed range, which is considered to have a global range. The identifier in the example has been defined in the global scope. Consider the following code:
Const int Spades = 1, clubs = 2, Hearts = 3, Diamonds = 4; Enum suits {spades = spades, // error Clubs, // Error Hearts, // Error Diamonds // Error}
Since the identifier in the front code has been defined in the global scope, an error message is generated. Note: Specify more than one program element with the same name, such as an enumerator and an object, which is considered a very bad programming method, should avoid use. In the precedent, this method causes an error.
Hidden name
You can hide this name by illustrating the name in a surrounded block. In Figure 2.1, i is described again in the inner layer, but hides the variables associated with I within the higher layer block.
Sample :: func (char * szwhat) {int L = 0; cout << "i =" << i << "/ n"; {INT i = 7, j = 9; cout << "i =" <
The program output given in Figure 2.1 is:
i = 0
i = 7
J = 9
i = 0
Note: Parameter SzWHAT is considered to be within the function range, so it is seen as an icon to be explained within the outermost block of the function.
Hidden name with file range
You can hide the name of the file range by clearly illustrating the same name over the block range. But the file range name can be accessed using the range resolution operator (: :). E.g:
#include int i = 7; // i has a file range that is described outside of all blocks (int Argc, char * argv []) {INT i = 5; // i has block range, hidden with files Range I cout << "block_scoped i HAS The value:" << i << "/ n"; couiue: << :: i << "/ n";}
The result of the previous code is:
Block_scoped i HAS The Value: 5
FILE_SCOPED I HAS The Value: 7
Hidden class name
You can explain a function, object, or variable, or enumerator to hide the class name by illustrating the same range.
Of course, class names can also be accessed using a keyword class.
/ / In the file range explanation ACCOUNT
class Account {public: Account (double InitialBaIance) {balance = InitialBalance;} double GetBalance () {return balance;} private: double balance;}; double Account = 15.37 // class name hidden Accountvoid main () {class Account checking ( Account); // Limited Acconut as class cout << "opening account with balance of: << checking.getbalance () <<" / n ";}
Note that when the class name is called anywhere, use the keyword class to distinguish it from the file domain variable Account, and when the class name appears in the left side of the range of argument (: :), no use rule. The names on the left side of the range of arithmeters are always considered to be class names. The following example shows that if you use keyword class, a pointer for an object of an object:
Class Account * Checking = new class account (account);
Account in the above statement has a file range in the initializer (in parentheses), the type is Double.
Note: In this example, the identifier name is reused that it is a bad program design style. More information about the pointers are "derived" behind this chapter. See Chapter 8, "Class" in the instructions and initialization of the class object. See Chapter 11, "Special Member Functions" for more information on using new and delete free storage operators. Form parameters of functions
The formal parameters of the function (the parameters specified in the function definition) are considered to be within the range of the outermost block of the function body.
Program and connection
A program consists of one or more conversion units connected together, starting from a conversion unit including the main function (concept) (see more information about the conversion unit, see "Pre-Processor Reference" translation stage".
For the main function, see "Program Start: Main Function" later in this chapter).
Connection type
The way to share objects or functions between the conversion unit is called "connection". These names are:
> Internal connections, that is, they only refer to program elements in their conversion units, not shared with other conversion units.
The same name in other conversion units can refer to different objects or different classes. Names with internal connections are sometimes considered to be partially relative to their conversion units.
An explanatory example of the name with the internal connection is as follows:
Static int I // static keyword ensures an internal connection
> External connections, that is, the program elements in any of the transition units in the program, sharing between the conversion unit. The same name in another conversion unit is identified as indicating the same object or class, and the name with an external connection is sometimes considered globally. An illustrative example of a name with an external connection is as follows:
Extern INT I;
> No connection, that is, the only entity, the same name in another range may not be the same object, such as an enumeration (but note, you can use no connection to pass a pointer to an object, which makes other conversion This object is accessible in units) The connection rule with the name of the file range is applied to the name of the file range (not typedef and enumerator name): l If a name is explicitly illustrated as static, then It has internal connections, identified in conversion
A program element within the unit.
> Enumerator name and TypeDef name are no connection
> All other names with file range are external connections
Microsoft Special Office
> If a function name with a file range is explicitly illustrated as inline, it has an external connection if it is instantiated or its address is referenced. Therefore, for a function with a file range, there may be an internal or external connection. Microsoft End End A class has internal connection, if:
> Do not use C features (such as members access control, member functions, constructor, destructive function, etc.)
> Not to illustrate another name with external connections. This limitation means that the class type object passes a function that has an external connection results in an external connection.
Connection with a range of name
The following connection rules apply to named names
> Static class members have external connections
> The class member function has an external connection
> Enumerator and TypeDef name are no connection
Microsoft Special Office
> The function that is illustrated for the Friend function must have an external connection. Describe a static function as Friend will be wrong.
Microsoft End
Connection with the name of the block range
The following connection rules apply to names with block ranges (local name):
> Description The name of Extern has external connections unless they are described above as static
> All other names with block range are no connection
Nameless name
Nameless name only:
> Function parameters
> Unlimited block range name for extern or static
> Enumerator
> The name illustrated in the typedef statement, and when the Typedef statement is used to provide a name for a unnamed class type, it is an exception. If the class has an external connection, the name may have an external connection. The following example gives the case where the TypeDef name with an external connection is given:
Typedef struct {short x; short y;} Point;
Extern Int Moveto (POINT PT);
The TypeDef name Point became the class name of the unnamed structure, which is used to illustrate a function with an external connection.
Because the TypeDef name is not connected, there is different definitions between the conversion unit, because the compiler is independently performed, so the compiler cannot check these different places, the result is that this type of error is to be connected Isolated. Consider the following scenario:
// Conversion unit 1
Typedef int int int INT
Int Myint;
...
// Conversion unit 2
Typedef short int int
Extern Int Myint
...
The previous code generates a "undeaded external" error when link.
The C function can only be defined within the file or class, and the following example describes how to define a function and give an error function definition:
#include void showchar (// Description function showcharvoid showchar (chat ch) // Define function showchar {// function has file range cout << ch;} struct char // definition class char {char show (); // Description SHOW function char GET (); // Description GET function char ch;}; char char :: show () // definition has a range of show functions {cout << ch; returnch ch} void Goodfuncdef (char ch // Define GoodFuncDef {Int BadFuncDef (INT i) // error nested function {RETURN I * 7;} for (int i = 0; i) cout; i) Cout < Connect to non-C functions: Only C functions and data with C connected to have c connection can be accessed. However, they must be defined in separate compiled conversion units. grammar Connection specification: Extern string text {Description Table OPT} Extern string text description Description Table: Description Description table description Microsoft C supports strings "C" and "C " in string text domains. The following example gives an explanatory description method with a name having a C connection: / / Description PrintF has a C connection EXTERN "C" int printf (const char * fmt, ...); / / Make the header file "All the contents in cinclude.h has C Extern "c" {#include} // Describe two functions with C connected Showchar and GetChar Extern "C" {char showchar (char ch); char getchar (void); // Define two functions with C connected showchar and getchar Extern "C" char showchar (char ch) {putchar (cH); return ch;} extern "c" char getchar (void) {char ch ;CH = getchar (); return ch} // Describe a global variable Errno with C EXTERN "C" int errno; Start and end By using two functions: Main and EXIT, make the program easily started and end. Other startup and end code may be executed. Program start: main function A special function called Main is the entry point of all C programs, which is not predefined by the compiler, but must be provided in program text. If you are writing a code attached to a single code program design mode, you can use the wide character version of Main. MAIN's instructions syntax is: Int main (); Or, optional: INT Main (int Argc [, char * argv [] []]]); WMAIN's instructions syntax is as follows: Int wmain (); or, optional: int WMAIN (int Argc [, wchar_t * argv [] [, wchar_t * envp []]); In addition, the Main and WMAIN functions can also be explained that the return value is Void (no return value). If you want to explain Main or WMAIN as return value void, use the RETURN statement unable to return to the parent process or operating system. When Main or WMAIN is illustrated as Void, if you want to return an exit code, you must use the EXIT function. Use WMAIN instead of Main In single code program design mode, you can define the wide character version of the main function. If you want to write the transplantable code attached to a single code specification, use WMAIN instead of Main. You use the MAIN similar format to describe WMAIN's formal parameters, and you can transfer wide character parameters and optionally wide character environment pointers to programs. WMAIN's ARGV and ENVP parameters are Wchar_T * types. If your program uses the main function, create a multi-byte character environment by the operating system at the beginning of the program, and a wide character copy of the environment is only created when needed. (For example, by calling the _wgetenv or _wputenv function). When calling _wputenv or first calling _WGETENV, if there is already an MBCS environment already exists, a corresponding wide character string environment is created, and by a _wenviron global variable, it is _Environ global variable Wide character version. At this point, the two copies of the environment (MBCS and single code) are exist at the same time, and the operating system is obtained in the entire survival of the program. Similarly, if your program uses the WMAIN function, create an MBCS (ASCII) environment when calling _putenv or GetENV, and pointing by the global variable _Environ. For more information on the MBCS environment, see Chapter 2, "Single-bytes and Multi-Transparent Collections" in the Microsoft Visual C 6.0 Runtile References of Microsoft Visual C 6.0 References. Parametery In prototype: Int main (int Argc [, char * argv [] [, char * envp []]); or INT WMAIN (int Argc [, wchar_t * argv [] [, wchart_t * envp []]); The parameters in the parameters allow for convenient parameter command line syntax analysis, and selectively access environment variables. The parameters are defined as follows: Argc Contains an integer of the number of parameters followed behind ArgV. The argc parameter is always greater than or equal to 1. Argv It is an array of space end strings that represent the parameters entered by the user's user in the command line. By conversion, Argv [0] is the command of the call, Argv [1] is the first command line parameter, so until Argv [Argc], it is always NULL. For more information on intercepting command line processing, see "Customizing C Command Line Processing" later in this chapter. The first command line parameter is always Argv [1], and the last one is Argv [ARGC-1]. Microsoft Special Office ENVP ENVP arrays are used in Microsoft C , and it is also a common expansion of many UNIX systems. It is a string array that is used to indicate variables set in the user environment. For information on intercepting environmental processing, see "Tailor C Command Line Processing" later in this chapter. This parameter is an ASI compatible in C, but it is not in C . Microsoft End The following example shows how to use Argc, Argv and Envp parameters in Main: #include #include void main (int Argc, char * argv []), char * envp []) {int inumberlines = 0; // The default is that there is no line number // If not only provides .exe file name, The list of command line options / n // The list of environment variables is the IF number (argc == 2 && SRTICMP (Argc == 2 && SRTICMP (Argc == 2 && SRTICMP) == 0) InumberLines = 1; // Through the string Table until you encounter NULL FOR (int i = 0; Envp [i]! = Null; i) {if (inumberlines) cout << i << ":" << ENVP [i] << "/ n" }} Wildcard expansion Microsoft Special Office You can use a wildcard question mark (?) And asterisk (*) to specify file names and path variables in the command line. Command line parameters are handled by routine programs called _setargv. By default, _Setargv extends wildcard to separate strings into the Argv string array, if the wildcard variable is not found, the parameters are transmitted as text. Microsoft End Analyze C command line variables Microsoft Special Office Microsoft C / C start code uses the following rules to explain the parameters given by the operating system command line: > The parameter is bound by the blank, which can be a space or a tab. > Insert characters (^) are not considered to be a escape character or delimiter. Before passing the argv array in the program, the character is fully processed by the command line syntax analysis program in the operating system. > Strings surrounded by double quotes ("string") is interpreted as a single parameter, regardless of whether there is a blank. The string enclosed by quotes can be embedded in parameters. > A double quotation marking (/ ") by the backslash is interpreted as a text double quotation character (") L backslash is explained as a text unless they follow one double quotation mark. > If the even backslash follows a double quotation mark, a backslash is placed in a backslash into the Argv array, and the dual quotes are interpreted as a string delimiter. > If the odd appearance is followed by a double quotation, a backslash is placed in a backslash into the Argv array, and the double quotes are "escape" by the remaining backslash and make a text double quotes. (") Placed in Argv. The following example shows how command line parameters are passed: Include void main (int Argc, // array argv "string number char * argv [], // command line parameter string array char * envp []) // Environment variable string array {int count; // Display each command line parameter cout << "/ ncommand-line arguments: / n"; for (count = 0; count Table 2.2 gives example input and expected output to illustrate the rules listed above. Table 2.2 Syntax Analysis Command Line Command line input argv [1] argv [2] argv [3] "ABC" D eabcdea /// bd "EF" g ha /// bde fgha /// "BC DA /" BCDA /// "BC" D EA // BCDE Microsoft End Custom C command line processing Microsoft Special Office If your program does not use command line parameters, you can save a small part of the space by intercepting the use of the library license program that executes the command line. This routine is called _setargv and is described in "Wildcard Extension". In order to intercept its use, define a routine in a file containing the main function, nothing, but to name _setargv; then to _setargv call will be met, no load The library version. Similarly, if you never access the environmental watches through the Envp parade, you can provide your own empty replacement environmental processing routine_setenvp. Just use the _setargv function, _setenvp must be explained as extern "c". Your program might call the spawn or exec routine cluster in the C running time library. If this is this, you cannot cancel the environmental handling routine because this routine is used to pass an environment from the parent process to the child process. Microsoft End Main function limit MAIN functions There are several restrictions that do not apply any other C functions. MAIN function: > Cannot be overloaded (see Chapter 12 "Reserved") > Can't explain to Inlinel can't explain that Staticl cannot take the address > Can't be called Program end In C , there are several ways to exit the program; > Call the EXIT function > Call an Abort function > Execute a RETURN statement from MAIN EXIT function The EXIT function described in the standard includes the file stdlib.h is used to terminate a C program. A value that is provided as an exit is returned to the operating system as a program return code or an exit code. Through the agreement, the 0 return code means that the program is successfully completed. Note: You can use the constant EXIT_FAILURE and EXIT_SUCCESS defined in stdlib.h to indicate the success or failure of your program. An Return statement is equivalent to a return value from the main function to call the EXIT function. For more information, see "EXIT" in the Microsoft Visual C 6.0 Running Reference. Abort function Also in the standard includes the Abort function described in the file stdlib.h for termination of a C program. The difference between Exit and Abort is that EXIT allows C to run termination processing (call global variable destructors), and Abort is the immediate termination program. For more information, see "Abort" in the Microsoft Visualc 6.0 Run Reference. RETURN statement A return statement is issued from main to the EXIT function. Consider the following example: int Main {EXIT (3); return 3;} In the above example, the exit and return statements are identical, but the C requires that the function should have a return type instead of the VOID when returning a value. The RETURN statement allows a value to be returned from the main. Additional start-up consideration In C , the structure of the object and the destructor can include executing user code, so it is important to understand what is initialized before entering Main and what is the destructor after being quit, is important (related to the constructor of the object and The destructor, see "Constructor" and "Destructor" in Chapter 11 "Special Member Functions") The following initialization occurred before entered Main: > Static data default initialization is 0. All static data without explicit initialization is set to 0 before performing any other code, including running initialization. Static data members must also be explicitly defined. > Initialization of global static objects in a conversion unit. Its occurrence may occur before entering main or before any function of the object or the object of the object or object. Microsoft Special Office In Microsoft C , global static objects are initialized before entering Main. Microsoft End Global static objects are interdependent with each other, but in different conversion units may have incorrect action. Additional termination consideration You can terminate a C program with exit, return, or abort. You can use the ATEXIT function to increase the exit processing, which is discussed in the next section. Use exit or return When you call EXIT or execute a Return statement from the main, the static object is destroyed in the order in which the initialization is reversed. The following example shows how to initialize and clear the work: #includeclass showdata {public: // Constructor Open a file Showdata (const char * szdev) {outputdev = fopen (SZDEV, "W");} // Destructure function Close a file ~ showdata () {fclose (outputdev);} // DISP function Shows a character on the output device String Void Disp (Char * SZDATA) {FPUTS (SZDATA, OUTPUTDEV);} private: file * outputdev; / / Define a static object of SHOWDATA, the selected output device is "con", the standard output device Showdata SDL = "con"; / / Define another type of static object for showdata, output directly to ShowData SD2 = "Con" in the file "Hello.dat", INT main () {"Hello to Default Device / N"); SD2.DISP ("Hello to File Hello.dat / N"); Return 0;} In the above example, the static objects SD1 and SD2 are created and initialized before entering main, and after using the RETURN statement to terminate the program, first destroy SD2 and then SD1. The destructor of the showdata class closes these static objects related files (for more information on initialization, constructors, destructuring functions, see Chapter 11 "Special Member Functions"). Another way to write this code is to illustrate the block range object showdata, and allow them to be exceeded The range is destroyed: Int main () {showdata SD1, SD2 ("Hello.dat"); SD1.DISP ("Hello to Default Device / N); SD2.DISP (" Hello to File Hello.DAT / N); Return 0} Use Atexit Using the ATEXIT function, you can specify an exit processing function to execute before the program terminates. No global static object initialized before the ATEXIT call is destroyed before exiting the processing function. Use Abort Call the Abort function immediately causes the termination, it has crossed the normal secting process of the initialized global static object, and has crossed any special processing specified by the ATEXIT function. Store Store the survival, connection, and processing of objects and variables in C . A given object can only have a storage class. This section discusses the C storage class of data: > Automatic > Static > Register > External automatic Automatically stored objects and variables are topical for a given example of a block. In recursive or multi-threaded code, automatic objects and variables are guaranteed to have different storage in different instances of a block. Microsoft C stores automatic objects and variables in the stack of the program. The objects and variables defined in a block are auto store unless specified with the extern or STATIC keyword. Automatic objects and variables can be specified with the AUTO keyword, but there is no need to explicitly indicate auto. Automatic objects and variables are unconnected. Automatic objects and variables continued to end to the end of the blocks they are illustrated. still The objects and variables illustrated for Static retain their values during the program execution. In recursive code, a static object or variable ensures the same state in different instances of a block code. Objects and variables of external definitions of all blocks have static survival and external connections. Explicitly explained a global object or variable for Static has an internal connection. Static objects and variables are continuous during the period execution. Register Only the parameters and local variables of the function can be explained as the register storage class. Like the automatic variable, the variable of the register continues only to the end of the blocks they have illustrated. The compiler does not allow the user to mark the register variable, vice versa, when global optimization is in use, the compiler makes its own register selection, but the compiler allows all Register keywords. External Objects and variables illustrated for Extern Describe an object that defines an object or a closed range having an external connection in another conversion unit. Description of Const variables with extern storage classes have external connections, and initialization of an ExternConst variable allows definitions in the conversion unit. In a conversion unit, it is initialized instead of defining in the conversion unit, which will generate uncertain results. The following example gives two extern descriptions: definedelsewhere (pointing to the name defined in a different conversion unit) and Definedhere (pointing to the name defined in a closed range): Extern int definedelsewhere; // Define void main () {int definedhere; {extern int definedhere; // points in closed range in another conversion unit;}} Object initialization A local automatic object or variable is initialized when the control process reaches its definition. A local static object or variable is initialized when the control process reaches its definition. Considering the following example, a class is defined in the example, which has been initialized and destructured, and then three objects I1, I2, and I3 are defined: #include #include // Define a class, which has been initialized and destructure class initdemo {public: initdemo {public: initdemo (const char * szwhat); ~ initdemo (); private: char * szobjname;}; ///InitDemo destructor INITDEMO :: InitDemo (const char * szwhat) {if (szwhat! = 0 && strlen (szwhat> 0) {// Distributes storage for SzobjName, then copy SzWhat initial value to Szobjname SzobjName = New char [strlen (SzWhat) 1]; strcpy (szobjname, szwhat); cout << "initializing" << Szobjnmae << "/ n";} else szobjname = 0;} // initdemo destructor INitDemo :: ~ INitDemo () {if (szobjName! = 0) {cout << "destroying:" << szobjname << "/ n"; delete szobjname;}} // Enter the main function Void main () {INITDEMO I1 ("Auto I1") {cout << "in block./n"; InitDemo I2 ("Auto I2"); Static InitDemo I3 ("static i3");} cout << "EXITED Block./n "; The above code describes how objects I1, I2 and I3 are in and when they are initialized and when they are destroyed. The output of the program is: Initializing: Auto I1 In Block.initializing: Auto I2 Initializing: Static i3 DESTROYING: Auto I2 Exited Block DESTROYING: AUTO I1 DESTRYING: Static i3 There are several points about the program: The first, I1 and I2 are automatically destroyed when the control flow exits defines their blocks. Second, in C , there is no need to explain the object or variable in the beginning of a block. In addition, these objects are only initialized when the control flow reaches their definition (I2 and I3 are examples of this definition), and the output is exactly when they are initialized. Finally, static partial variables, such as I3, retain their values during the duration of the program, but is destroyed at the end of the program. Types of C supports three object types: > The basic type is built in a language (such as int, float or double). Examples of these basic types are often referred to as "variables". > Detective class is a new type of derived from the internal type. > The class type is a new type created by the existing type combination, which is discussed in Chapter 8 "Class". basic type The basic type in C is divided into three categories: "integer", "floating point" and "void". Integer can handle all numbers; floating-point types can specify values that may have fractional portions. Void Type Description Value Empty Set. The VOID type variable cannot be specified, which is basically used to explain the "universal" pointer of the data without the return value or indicating that there is no type or any type of data. Any expression can explicitly convert or transform to type Void, but these expressions are limited to the following applications: > An expression statement (see Chapter 4 "Expression"). > The left side operand of the comma operator (see "Command Operators" in Chapter 4 "Expression"). > Conditional operator (? :) of the second or third operand (see "Expression" in Chapter 4 "Expression"). Table 2.3 explains the type of type size, which is independent of Microsoft. Table 2.3 Basic Types of C languages Directory Type Content Integer CHAR Type Char is integer, usually contains members of the character set, in Microsoft C , this is the ASCII code C compiler to treat variables for type CHAR, SIGNED CHAR, and UNSIGNED CHARs as different types . Variables of type char are increasing to int, as they default to Signed Char unless the / j compile options. In this case, they are used as the type unsigned char, and the Intshort type short int (or short) that is booming without a symbolic extension is a size, greater than or equal to the size of the char type, less than or equal to the int type. Size Short Type Objects can be illustrated as Signed Short or unsigned shortsigned short is the synonym INT type INT is integer, it is greater than or equal to the size of the short int type, less than or equal to the size of the size INT type of the type LONG can be explained. For Signed Int or Unsigned Int. Signed int is the synonym of INT_INTN Specifies the size of the integer variable, where N is a size given in a bit-based unit, and the value of n can be 8, 16, 32 or 64long type long (or long int) is greater than or Equal to the size of the type INT, an object of the Type LONG type, can be explained as Signed long or unsigned longsigned long is a synonym floating point float type float is the smallest floating point type Double type Double is a floating point type, it is greater than or equal to Float type size, but less than or equal to the size of the long double * Type Long Double is a floating point type equal to type Double * Long Double and Double representations are identical, but Long Double and Double are two types. Microsoft Special Office Table 2.4 lists the storage space required for basic types in Microsoft C . Table 2.4 Basic type size Type size char, unsigned char, soud, unsigned short2 byte, unsigned int4 type long, unsigned long4 byte float4 byte Double8 byte long double * 8 bytes * Long Double and Double representations are identical, but Long Double and Double are two types. For more information on type conversion, see Chapter 3, "Standard Conversion". Microsoft End Specify the integer Microsoft C also supports the integer of the specified size, you can use the __intn type indicator to explain 8, 16, 32 or 64-bit integer variables, where n is the size of the integer variable, the n value can be 8, 16, 32 , Or 64. The following example describes a variable for each of these specified sizes: _ _INT8 nsmall; // Description 8-bit integers _ _INT16 NMEDIUM; // Description 16 integers _ _INT32 NLARGE; / / Description 32-bit integers _ _int64 nhuge; // Description 64-bit integer type __INT8, _INT16 and _ _INT32 are synonyms with the same size ANSI type, which is useful to write the same portable code as the behavior in multiple platforms. Note that __ int8 data type is synonym of type char, _INT16 is synonym of type Short, __ int32 is synonym of type int 3, __ int64 data type is not equivalent in ANSI. Because __int8, __ int16 and __int32 are considered to be corresponding synonyms by the compiler, it should be careful when using these types of parametric de-load function. For example, the following C code will generate a compilation error. void myfunc (_ _int8) {} void main () {_ _int8 newval; char mychar; myfunc (mycha); // unclear function call; MyFunc (newval); // char with _ _INT8 is synonym. } Derive type The derived type can be used in the program, which can include a new type of direct derived type and a compound derived type. Directly derived type The new type of direct derived from the existing type is pointing, indicating, or (in the function situation) transmitted type data to return a new type of type. > Variables or object arrays > Function l A given type pointer > Items' reference > Constant > Class member pointer Variables or object arrays Variables or object arrays can contain specified specific types, for example, an array from integer derivatives is an array of INTs. The following code example describes and defines a 10 INT variable array and an array of 5 objects containing class SampleClass: Int Arrayofint [10]; Sampleclass asampleclass [5]; function Functions have 0 or more references for references and objects that return to specified types (or not to return, if the function has a VOID return type). A given type pointer Variables or pointers of the object select one of the memories. The object can be globally, partially (or stack structure) or dynamically assigned. A given type of function pointer allows the program to delay the function of a function or multiple objects until running. The following example gives a variable that points to type CHAR Pointer definition: CHAR * SZPATHSTR; The reference to the object's reference object provides a convenient method by reference access objects, but the same syntax as required by value access objects. The following example describes how to use a reference to function parameters and as a function return type: BigclasStype & func (BigclassType & ObjName) {ObjName.dosomething (); // Note that the member operator (.) ObjName.SOMEDATA = 7; // The data passed through a non-Const reference is modified. Return Objname;} Several points about the object delivery of the object by reference is: > Accessing Class, Struct, and UNION objects are the same, as they pass values: member operators (.). > Unable to copy objects before the function call, pass their address, which reduces the system overhead of the function call. In addition, returning a reference function only needs to receive the address of the objects they refer, not the copy of the entire object. Although the above example is merely a reference in context communication, reference is not limited to this application. For example, consider a function of a function that requires a l value - a normal requirement of the overload operator: class vector {public: point & operator [] (int nsubscript); // function returns a reference type ...}; The above instructions specify a user-defined subscript operator for class vector. In one assignment statement, there are two possible states; Vector VL; INT i; POINT P; VL [7] = p; // vector used as a l value P = VL [7]; // Vector as a R value The latter case, that is, VL [7] is used as a R value, Can be implemented without reference. However, the former case, that is, VL [7] is used as a l value, and if the function that does not use the reference type, it cannot be easily implemented. From the concept, the last two statements in the previous example translate to the following code: VL.Operator [] (7) = 3; // vector as a l value i = VL.Operator [] (7); // vector used as a R value When you look at this way, it is easy to see that the first statement must be an L value, and the left side of the assignment statement is correct. For more information on overloading and heavy load operators of special circumstances, see "Overloaded Operators" in Chapter 12. You can also use a reference to explain a constant reference to a variable or object. A reference to Const retains the performance of the transfer parameter by reference, and prevents the modified function to modify the initial object. Consider the following code: // invalue is a const reference. Void Printint (Const Int & IntValue) {Printf ("% D / N", INTVALUE); Reference initialization is different from the assignment of a variable of a reference type, considering the following code: INT i = 7; INT j = 5; // Reference Initialization INT & RI = I; // Initialization Ri point to IINT & RJ = J; // Initialize RJ pointing J. // Assignment ri = 3; // i is now equal to 3RJ = 12; // j is now equal to 12RI = RJ; // i is now equal to (12). constant For more information on the various constants allowed in C , see "Text" in Chapter 1, "Specification". Class member pointer These pointers define a type pointing to a special type of class member, such a pointer can be used by any object of any object or class type derived type of class type. Using class members pointed to enhance the type security of the C language, as listed in Table 2.5, three new operators and structures can be used. Operators and structures used by table 2.5 and members Operator or Structure Syntax Using :: * Type :: * Ptr-Name Member Pointer Description. * Obj-name. * PTR-name Use an object or object reference to indirectly reference a member pointer, for example: int J = Object. * PMyType -> * Obj_ptr -> * PTR_NAME uses an object pointer to indirectly reference a member pointer, for example : int J = POBJECT -> * PMYTYPE Considering the following example, the example defines a class ACLASS and a derived type PDAT, which pointing Member i1: #include // Define class aclass {public: int I1; show () {cout << i1 << "/ n";}}; / / Define a derived type PDAT, point to I1 members of the object of the type ACLASS Int aclass :: * pdat = & aclass :: I1; void main () {aclass aclass; // Defines an object of type ACLASS. ACLASS * PACLASS = & aclass; // Defines a pointer to the object. INT I; ACLASS. * PDAT = 7777; // Use. * Operator pair aclass :: I1 assignment aclass.show (); i = paclass -> * pdat; // * operator indirect reference a pointer Cout << i << "/ n";} member PDAT pointer is a new type derived from class ACLASS, which is a more strong type than INT "normal" pointer, because it only points to int member of class ACLASS (here) I1). The static member's pointer is a normal pointer instead of a class member pointer, considering the following example: Class HasstaticMember {public: static int design; INT HasstaticMember :: SMEMBER = 0; INT * psmember = & havetaticmember :: Smember; Note that the type of this pointer is "int pointer" instead of "HasstaticMember :: INT" pointer ". Member pointers can be pointed to the member function as the member data, consider the following code: #include // Describe a base class A with a virtual function Identify, (Note that Struct is the same in this context) Struct a {virtual void identify () = 0; // class A does not define}; / / Note Identify member functions a pointer Void (A :: * Pidentify) () = & a :: identify; // Description Class BSTRUCT BPUBLIC A {Void Identify ();}; // for class B definition Identify function void B: Identify () {Printf ("Identification IS B :: Identify / N);} void main () {b Bobject; // Description Type B Object A * PA; // Description Type A Pointer PA = & BOBJECT; / / Make PA Point to an object of type B (PA -> * PIDENTIFY) (); // Call the Identify function} through the member PIDENTIFY pointer} The output of the program is: Identification is b :: Identify This function is called by a pointer to the type A. However, since the function is a virtual function, the correct function of the object referred to in PA is called. Composite derived type This section describes the following compound derived types: > Class > Structure > United Initialization of the collection type and collection type can be found in Chapter 7, "Set Initialization" in "Designation". class Class is a set of member objects that combine together, operate these members' functions and (optional) member objects and functions access control specifications. By packeting the objects and functions in the class, C allows programmers to create derived types, not only to define data, but also define the behavior of the object. Class members are private access and private inheritance in the default. Chapter 8 "Class" intermediary profile. Access control is included in Chapter 10 "Members Access Control". structure The structure of C is the same, and the difference is that all member data and functions are public access, and inheritance is default for public inheritance. For more information on access control, see Chapter 10, "Members Access Control". joint The joint allows programmers to define the type of different variables in the same memory space. The following code gives how to use a combined storage several different types of variables: / / Description You can have a combination of data type CHAR, INT, and CHAR * Union Toprint {char chvar; int ion; char * szvar; / / Describe an enumerated type for describing the type of print ENUM PRINTTYPE {CHAR_T, INT_T, STRING_T}; Void Print (TOPRINT VAR, PRINTTYPE TYPE) {Switch (Type) {Case Char_t: Printf ("% C", Var.chvar; Break; Case INT_T: Printf ("% D) ", Var.ivar); breaf; case string_t: printf ("% s ", var.szvar; Break;}} type name The synonyms of the basic and derived types can be defined using the typedef keyword. The following code describes the use of TypedEf: Typedef unsigned char Byte; // 8 unsigned entity Typedef byte * pbyte; // Pointer to Byte Byte ch; // Describe a variable of a type byte PBYTE PBCH; / / Describes a pointer to the Byte variable The above example gives a unified instructions for the basic type unsigned char and its derived type unsigned char *. The TypeDef structure is also useful for simplified instructions. A TypedEf means defines a synonym, not a new independent type. The following example illustrates a type name (PVFN) indicating a pointer to the function of returning the type of VOID. The advantage of this description is that the array of these pointers in the later program is very simple. // Two functions prototypes Void func1 (); Void func2 (); // Define PVFN to indicate a pointer to a function pointing to the return type VOID TYPEDEF VOID (* PVFN) (); ... / / Describe a function pointer array PVFN PVFN [] = {FUNC1, FUNC2}; // Call a function (* pvfn [1]) (); l value and r value The expression in C can evaluate "L Value" or "R Value". The L value is an expression that evaluates a certain type of non-Void and specifies a variable. The l value appears on the left side of the assignment statement (therefore represented by "L"), the variable typically l value can be unmodified by the const keyword, which cannot appear on the left side of the assignment statement. The reference type is always a l value. The term R value is sometimes used to describe a value of an expression and is separated from one L value, all L values are R value, but the R value is not all L value. Some examples of correct and wrong use; i = 7; // The correct variable name i is a l value 7 = i; // Error constant 7 is a R value J * 4 = 7; // Error Expression J * 4 Generate a R value * p = i; / / correct one indirect reference pointer is a l value Const int Ci = 7; // Description a const variable Ci = 9 // CI is an unmodified L value, so assigning a value caused an error message generation. ((i <3)? i: j) = 7; // correct, conditional operator (? :) Returns a l value Note: The example of this section describes the correct and error usage of the operator unloaded, through the overload operator, you can make an expression, such as J * 4 a l value. Limit Two standards include files Limits.h and float.h define the "number restrictions" or a minimum and maximum value that can be taken for a given type variable. These minimum and maximum values ensure any C represented by the same data as ANSI C. Compilers are portable. Limits.h contains the restriction of the file to integer definition, float.h is the limit of the floating point type definition. Integer limit Microsoft Special Office Integer Type Restrictions are listed in Table 2.6, which are defined in the standard header file Limits.h. Table 2.6 Restriction constant of integer constants Constant Meaning CHAR_BIT is not a minimum variable of the bit field 8Schar_Minsigned CHAR type Variables - 128schar_maxsigned CHAR Type Variables 127uchar_maxunsigned CHAR Type variable Maximum value 255 (0xFF) CHAR_MINCHAR type variable Minimum value -128; if used / J option is the maximum value of 0CHAR_MAXCHAR type variable; if the / j option is 255MB_LEN_MAX in the maximum number of bytes in multi-character constant, the minimum value of the maximum number of variables - 32768SHRT_MAXSHORT Type Variables 32767USHRT_MAXUNSIGNED SHORT Type Variables 65535 0xFFFF) 2147483647ULONG_MAXunsigned long type variable maximum value of the minimum value of the maximum value of the variable type -2147483647-1LONG_MAXLong 4294967295 maximum 2147483647UINT_MAXunsigned int type variable type variable minimum -2147483647-1INT_MAX INT_MIN type variable (0xffffffff) LONG_MINlong type variable 424967295 (0xfffffff) If the value exceeds the maximum integer representation, the Microsoft compiler generates an error. Microsoft End Floating point limit Microsoft Special Office Table 2.7 lists the restrictions of floating point constant values, which are defined in the standard header file float.h. Table 2.7 Floating point constant limit Constant meanings FLT_DIG 6DBL_DIG 15LDBL_DIG Digital number q, that is, the floating point number with Q decimal numbers can be placed as a floating point representation, and returns the minimum positive number X of 15FLT_EPSILON, such as X 1.0 is not equal to 1.01. 19202896E-07FDBL_EPSION 2.2204460492503131E-016LDBL_EPSION 2.2204460492503131E-016FLT_GUARD 0FLT_MANT_DIG The number of digital bits in the 24dBL_MANT_DIG base specified by FLT_RADIX in the floating point valid number. Radix 2; 53LDBL_MANT_DIG so these values specified number 53FLT_MAX maximum representable floating-point 3.402823466e 38fDBL_MAX 1.7976931348623158e 308LDBL_MAX 1.7976931348623158e 308FLT_MAX_10_EXP largest integer number that is a power of 38DBL_MAX_10_EXP 10 may represent a floating point 308LDBL_MAX_10_EXP 308FLT_MAX_EXP maximum integer, FLT_RADOX power 128DBL_MAX_EXP this number is the smallest positive floating-point number can be represented by 1024LDBL_MAX_EXP 1024FLT_MIN 1.175494351e-38FDBL_MIN 2.2250738585072014e-308LDBL_MIN 2.2250738585072014e-308FLT_MIN_10_EXP minimum negative integer, the number is a power of -37DBL_MIN_10_EXP 10 represents a floating point -307LDBL_MIN_10_EXP -307FLT_MIN_EXP minimum negative integer power FLT_RADIX this number is expressible -125DBT_MIN_EXP float -1021LDBT_MIN_EXP -1021FLT_NORMALIZE0FLT_RADIX index represented by the floating point addition of base 2_DBL_RADIX2_LDBL_RADIX2FLT_ROUNDS rounding mode 1 (near) _DBL_ROUNDS1 (near) _LDBL_ROUNDS1 (near) Note that the information in Table 2.7 may vary in the future version of the product. Microsoft End