Hello, C ++ (3) 2.1 self-white of a C ++ program, 2.1 self-white

Source: Internet
Author: User

Hello, C ++ (3) 2.1 self-white of a C ++ program, 2.1 self-white

Part 1: First close contact with C ++

After browsing the world map of C ++, I had a basic understanding of C ++ and entered the door of the C ++ world. So how can we bring another foot into the door of the C ++ world? Should I start writing C ++ programs immediately? Or ......

While we are hesitating, we can see a group of C ++ beginners who are filled with question marks. Let's take a quick look. Oh, it turns out that a C ++ program is introducing itself.

2.1 self-white of a C ++ Program

"Hello everyone, welcome to the wonderful C ++ world. I am a welcome to the CIDR world, the simplest and most common CIDR program. My name is helloworld.exe ". Although simple and common, I am almost the most famous C ++ program in the world. Every beginner who has come to the C ++ world has been in close contact with C ++ for the first time through me. Before listening to my introduction, you will surely feel that the C ++ program is very mysterious. For example, how is the C ++ program created? What components does a complete C ++ program consist? What is the legendary source file? How is the C ++ Program executed? In fact, our C ++ program is not mysterious at all. Like everyone else, we have our own mom and dad, our facial features, and our own life processes. What? What do you think is incredible? Don't worry. Let me hear you here ......"

2.1.1 use Visual Studio to create a C ++ Program

The first thing that interest everyone most in the C ++ world is to create a C ++ program. Most C ++ programs are created through a software called Integrated Development Environment (IDE). It can be said that it is a factory for creating C ++ programs. Although there are many integrated development environments that can be used to create C ++ programs, we prefer Visual Studio developed by Microsoft. As an integrated development environment that has been evolving over the past 20 years, Visual Studio has a variety of different features: flagship edition for large-scale team development, professional edition for personal development, there is also a free quick version. If we only want to use Visual Studio for C ++ learning, we can use the Visual C ++ Express version. It is not only fully functional, but also small. More importantly, it is free. We can download and install it from Microsoft's website for free. Visual Studio is the most common development environment on the Windows platform. For other development tools and development tools on the Linux platform, see Section 2.3 In the following document.

Now, under my guidance, please use Visual Studio to create our first C ++ program step by step. Step 2: Create a project. Find the installed Visual Studio from the Start menu and click Start. When Visual Studio is started for the first time, it requires us to select the interface layout settings. Here we select the layout settings for Visual C ++, then, after a while, you can see the start page of Visual Studio Lili. In Visual Studio, all our development work is performed in a project. Therefore, the first step for us to write programs using Visual Studio is to create a project for managing program files: click "new project" on the left of the start page. In the "new project" dialog box that appears, select the "Visual C ++" node in the tree chart on the left, select the "Empty Project" Project template from the project type list on the right, enter the project name "HelloWorld" at the bottom of the dialog box, and select the project storage location, click "OK" to create a new project.

Figure 2-1 create a project

Step 2: add the source file. Creating a new project only sets up an empty framework and waits for us to add some substantive content to it. In Solution Explorer on the left, locate the "source file" branch under the "HelloWorld" project, right-click the "source file" branch, in the pop-up menu, select "Add-> new item" to obtain the "Add new item" dialog box. In the "Add new project" dialog box, select the "Visual C ++" branch in the tree on the left, and then select "C ++ file" in the file type list on the right ", then, change the file name to "HelloWorld. cpp, and click OK. Visual Studio creates a new HelloWorld for us. cpp source file and add it to the project.

 

 

Figure 2-2 add source files

Step 2: edit the code. With the blank source file, it is equivalent to the painter's drawing board. After the writer has prepared the manuscript paper, he will wait for us to start coding. In the opened HelloWorld. cpp file, we edit the following code (here, we note that the punctuation in the code should be in English ):

# Include <iostream> using namespace std; int main () {// output "Hello World!" on the screen !" String cout <"Hello World! "<Endl; return 0 ;}

Figure 2-3 edit code

Step 2: Compile the execution program. After the code is edited, We can compile and execute this program to say hello to the C ++ world. In this step, you can use the menu command "debug-> start execution (do not Debug)", but in more cases, we can use the Ctrl + F5 shortcut to complete the process. After pressing the shortcut key, Visual Studio will compile the source file in the project. If there is no error in the source file, the hacker will generate the corresponding helloworld.exe executable file. Then the program will be started to print a "Hello World!" in the DOS window !" The string greets the C ++ world.

 

Figure 2-4 Hello World!

Best Practice: Wait a moment. I haven't seen the output yet!

When we execute a program in Visual Studio, if the program does not need to interact with users during execution, the DOS window opened during execution will be closed immediately after execution. If this program has output results, we cannot even see the output results of the program. After a program is executed, the output results cannot be viewed clearly. How can this problem be solved?

To solve this problem, we can add a "system (" pause ");" statement before the main function of the program returns. For example:

Int main (){//... // Pause system ("pause"); return 0;} before the end of the program ;}

After this statement is added, the program will be suspended before execution. In this way, we have enough time to see the output results of the program. Naturally, this statement can also be used in places that need to be paused during program execution to improve the program's interactivity.

Another way to view the program output result is to start the DOS window and then manually execute our application in the DOS window. In this way, the DOS window is not closed after the program is executed, so we have time to view the program output results.

After four simple steps, we easily wrote our first C ++ program and completed our first close contact with C ++. In addition to using Visual Studio to create C ++ programs, we can even create C ++ programs in a purely manual manner. However, the basic processes are the same regardless of the method. If Visual Studio is used, the development efficiency is relatively high because of the help of development tools. If you are using a manual method, you can flexibly customize the entire development process to meet some of our personalized needs. For beginners, the manual method is a little complicated. The best way to learn is to get started with Visual Studio. When there is a certain foundation, you need to have more detailed control over the programming process, and then use the manual method. In this way, it will not be trapped by complicated manual methods at the entry stage, but will be limited by development tools after the advanced stage.

2.1.2 C ++ program = pre-compiled commands + program code + Comments

The sparrow is small and dirty. Don't look at me. I only have a few lines of code, and the implementation function is very simple. But I also have the "facial features and limbs" of the C ++ program ": pre-compiled commands, program code, and comments, as shown in 2-5. In most cases, these three basic components are put in a text file with the extension "cpp", which is called a C ++ source file. The source file records my "five senses and four limbs" and planned my life. The source file writer is my designer. By modifying the source file, you can change my face and path of my life, so that I can complete various tasks and implement various functions.

 

Figure 2-5 C ++ program = pre-compiled command + program code + comment

Next, let's take a look at my source files and learn about my "facial features and limbs ".

1. Pre-compiled commands

In the source file, the content starting with "#" is the pre-compiled command. It is used to tell the compiler to pre-process the source file, such as inserting the file, replacing the string, and so on before it is actually compiled to get the final source file involved in compilation. For example, in my source file HelloWorld. cpp, the first line is a pre-compilation command for inserting files:

#include <iostream>

The "# include" command is used to insert the specified file into the location of the command as part of the entire source file. Because such a file is always inserted in the header of a source file, we usually call it a header file ). Here, we insert the header file "iostream", because we need to use the cout and endl defined in the program to complete the output (about the input and output of C ++, for more information, see section 2.2 ). Note that the file name after the "# include" command has two Representation Methods: If you use double quotation marks "to enclose a file name, when the Preprocessor processes this command, search for the file in the current directory (that is, the directory where the source file is located). If the file does not exist, search for the file in the project's include directory (including the project's default header file directory, that is, the "\ VC \ include" folder under the Visual Studio installation directory, and the project additional header file directory set in the project properties) to search for this file; if you use angle brackets <> to enclose a file name, The Preprocessor will directly search for the file in the project's include directory. Therefore, we usually use "" to insert the header files under the current project directory (such as the header files we have created ), use <> to insert the library header files (such as iostream) under various project inclusion directories ). It is worth reminding that all punctuation marks used in the Code (the angle brackets used here, including double quotation marks, commas, semicolons, etc. used in the code below) must be in English. Some Chinese and English symbols are very similar and are easily confused by beginners, causing compilation errors. This is especially worth the attention of beginners.

2. program code

The program code body consists of several C ++ statements (a line of code ending with a semicolon is usually a statement). It can be said that a statement is the basic unit of a program. In my source file, the first C ++ statement is:

using namespace std;

This statement indicates that the namespace I use is std. The so-called namespace is various identifiers in the Program (for example, cout and endl here, we use these symbols to access various elements in the program, which can also be called the names of these elements, therefore, these symbols are also called identifiers. For more information, see Section 7.3.2 about namespaces. In C ++, any identifier is defined in a namespace, and the same identifier can be defined in multiple namespaces at the same time. This is just like a man in Zhangjia village named Chen liangqiao and Chen liangqiao in Lijia village. When everyone calls Chen liangqiao, we must add a prefix before the name, such as "Chen liangqiao of Zhangjia Village" or "Chen liangqiao of Lijia village ". The namespace in C ++ is equivalent to the "Zhangjia Village" and "Lijia Village" here ". Here, the cout and endl we use in the code below are all from the std village, so we use this statement to tell the compiler that if there is an identifier without a prefix (for example, here's cout), you can go to the std village to find it. If you can find it, it is it (as a result, std: cout is found in the std village ). Most of the content of C ++ is defined in the std namespace. Therefore, we often need to use this statement in the Code to introduce the std namespace. Of course, if you do not use this statement, you can add a namespace prefix before the identifier to explicitly indicate that this is an Identifier from a namespace (in code, use std:: cout instead of cout, use std: endl instead of endl ).

The following statement is:

int main()

This statement, together with the content in the braces following it, forms the main () function, also known as the main function. A function is the most basic organizational unit in a C ++ program. It organizes several statements to implement a function. If a statement is equivalent to a cell of the human body, the function is equivalent to an organ consisting of several cells with certain functions. The main function here is the most important "organ" in a program ". A c ++ program must have one primary function and only one primary function. When the C ++ program starts to execute, it first enters the main function, and then executes the statements one by one until the statements are executed and exited from the main function, and the program execution ends. It can be said that the main function defines the life of a C ++ program.

Know More: Why must a C ++ program have only one main function?

After we double-click the execution program, the process of the execution program will first create the main thread, the main thread then calls the Convention to start the Runtime Library, and the started Runtime Library calls the agreed main function, since then, the user's code has been executed. The main function is the execution entry of the main thread. Therefore, a C ++ program must have a main function.

At the same time, a thread cannot have multiple execution portals. In C ++, a global symbol (variable or function) can only have one definition. As a global function, the main function can only have one.

The following is a statement in the main function:

cout<<"Hello World!"<<endl;

Cout is an output stream object defined in the header file "iostream". It is a pre-defined object in the C ++ standard library and is usually used to output text or numbers to the screen. Previously, the "# include" pre-compiled command contains the "iostream" header file to use this object in code. The input/output stream will be described in more details in later sections. Here, you only need to know this statement and you can set "Hello World !" Output the string of text to the screen. It is worth reminding that the double quotation marks here must also be in English.

My last statement is:

return 0;

It indicates that the program is successfully executed and return (return ). Generally, a value of 0 is returned, indicating that the program is successfully executed. (If an error occurs during the execution of the program, other values indicating the error message can also be returned. The executor of the program can accept the returned value to determine whether the program is successfully executed ). At this point, the statements in the main function have been executed, and my life has ended.

3. Notes

Annotation is the source code editor to help readers of the Code (Code maintenance personnel, including the writers themselves) better understand the code, some explanatory texts written in the code about a line or piece of code. Although the comments in the source code are not involved in the final compilation and will not affect the functions of the program, it will improve the readability of the code and bring great convenience for later maintenance. For example:

// Output "Hello World!" on the screen !" String

Is a comment, which explains the role of the next statement, so that we can have a better understanding of the Code.

In form, comments in C ++ can be divided into single-line comments and block comments. "//" Is a single-line annotator. "//" is followed by a comment until all the contents of the line feed are comments. Because there is only one line of content, it is often used to give a brief explanation of the Code. For example, the comment above is a typical single line comment.

Block comments in C ++ are represented by a pair of "/*" and "*/". All contents that appear between these symbols are comments. Because it can contain multiple lines of content, you can use block annotations when you need to explain the code in detail. For example:

/* This is a comment */

In terms of function, comments are generally divided into preference comments and explanatory comments. Most of the comments are at the beginning of the program source file. They are used to describe the program file name, purpose, writing time, and maintenance history. In the above example, we can add a preamble to the first line of the source file to explain the functions of this source file:

// HelloWorld. cpp: output "Hello World!" on the screen !" String

Preamble are widely used in large projects. Generally, each project has its own defined format of preference comments, which is used to explain necessary information to the readers of the Code. The following is a preference comment extracted from an actual project. It illustrates the name, role, modification history, and other information of the source file, helping readers better understand the code. You can use this as a template to compile your own preface comments.

///////////////////////////////////////////////////////////////////////// AppDataView.cpp : implementation file////CAppDataView//  This view is designed to display the App Data//// Version: 2.1// Date: September 2001// Author: Chen Liangqiao// Email: chenlq@live.com// Copyright (c) 2002. All Rights Reserved.////   History:/*27.09.2001       Chen Liangqiao                        Added OnCreate(), OnUpdate():                        Added usage of mesh tracer layers                        Added bugfix for Graphics zoom error30.10.2001       Chen Liangqiao                        Changed order of MPR View only in _TORCHTONAV08.11.2001       Zeng Me                           Added EUpdateReason, used for UpdateAllView(),                        Added voxel trafo                        Changed the control panel due to new CTestCtrl*////////////////////////////////////////////////////////////////////////

Unlike the initial part of the source file, the explanatory part is mostly scattered in various parts of the source code. It is used to explain the meaning of the Code to the code reader and explain some necessary problems. For example, note in the example above:

// Output "Hello World!" on the screen !" String cout <"Hello World! "<Endl;

This explanatory comment is used to explain to the code reader the function of the code below is to output the string "Hello World !".

Best Practice: what is a good comment

Although program comments do not affect the implementation of program functions, the compiler will not read our comments, but good comments can increase the readability of program code and make the program easier to maintain. No one is willing to maintain a code without comments, which is tantamount to reading tianshu. So what kind of annotation is a good annotation?

First, the comment must be noted.

Annotations are "prompts and instructions" for the code to help readers better understand the code. When we think that the Code cannot be "viewed at a glance" and need to be explained, or the code needs to be specifically described, we should add comments and provide additional explanations and instructions to help readers understand the code. For example:

// Determine whether a floating point is an approximate integer bool is_int (double d) {// subtract the integer (int) d from the floating point d, returns the decimal part double s = d-(int) d; // determines whether the decimal part is in the error range if (s> 0.000001) return false; else return true ;}

The comments here properly explain the code that is hard to understand (if there is no comment, it is difficult to understand "double s = d-(int) d at once;) to improve the readability of the Code.

Second, it is best not to comment out the areas that should not be commented out.

Note is just a "prompt and description" of the Code. If the Code itself can be well-understood, there is no need to make a comment. Note that the comment is only a short descriptive text, not a detailed document. Program comments cannot be overwhelming. Too many comments will be dazzled, reducing the readability of the Code. For example, annotations in the following code are not suitable:

// Determine whether a floating point number is an approximate integer. // Its Parameter indicates the input floating point number d. // Its return value indicates whether the input is an approximate bool value bool is_int (double d) {// subtract the integer from the floating point to obtain the fractional part. // Where, d indicates the floating point, and (int) d indicates the integer part of the floating point. double s = d-(int) d; // determine whether the fractional part is in the error range if (s> 0.000001) return false; // if the fractional part is greater than the error range, it indicates that the floating point is not an approximate integer, returns false else return true; // If the fractional part is smaller than the error range, it indicates that the floating point number is an approximate integer and returns true}

The comments in this section of code also provide a detailed explanation of some code that is easy to understand. The content of the comments far exceeds the content of the Code, which not only does not increase the readability of the Code, on the other hand, code is overwhelmed by complicated comments, which reduces the readability of the Code. This annotation is an extra effort.

In addition, you should develop a good habit of coding comments. Add necessary comments when writing the code, modify the corresponding comments when modifying the code, and delete useless comments to ensure the consistency between the comments and the code.

Annotations should be accurate and easy to understand to avoid ambiguity. Incorrect comments are not helpful but harmful.

The location of the comment should be adjacent to the described code. It can be placed above or right of the code, not below. For example:

// Output "Hello World!" on the screen !" String // comments the code below cout <"Hello World! "<Endl; int n = 1024; // Number of loops, comments on the code on the left

If the code is long, especially when multiple nesting occurs, comments should be made at the end of some paragraphs to view the starting and ending positions of the nested structure. For example, a code with multiple loops and its comments are as follows:

For (int I = 0; I <100; ++ I) {for (int j = 0; j <100; ++ j) {// algorithm processing ...} // j loop end} // I loop end

The program code is not only written to the compiler, but also to the programmer himself or others. For the compiler, it doesn't matter whether there are comments in the Code. However, for programmers who read the code, the appropriate comments can greatly improve the readability of the Code and make the code easier to maintain. Therefore, annotation is an essential part of the C ++ program code, and whether the program code contains appropriate annotations has become a standard for measuring whether a programmer is excellent.

Pre-compiled commands, program code, and comments constitute my "five senses and four limbs", but at this time I am still a text file suffixed with cpp, to get the final executable exe file, I had to rely on my father's mother: compiler and linker.


Hello, I am a C beginner. I am a DPF version of the third edition of "C program design question and Machine Guide,

I suggest reading books from abroad
 
Hello, you can give me a USB \ VID_13D3 & PID_5094 & MI_00 \ 6 & 302321C3 & 0 & 0000 this ID of the camera driver k50i xp

Dear Asus user.
We recommend that you download the following driver: support.asus.com.cn/..20.9.zip
 

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.