Basic C language tutorial (I) Highlight colors

Source: Internet
Author: User

First, take a look at the following simple C program and guess what it will do. It doesn't matter if you can't guess it. I will explain it in detail later.
# Include <Stdio. h >

Int main (void)/* a simple program */
{
Int num;/* define a variable named num */
Num = 1;/* assign 1 to num */

Printf ("This is a simple C program. \ n");/* call the printf function */
Printf ("My favorite number is % d because it is first. \ n", num );

Return 0;
}

Before you describe this program in detail, I want to useCompilerPut itCompileCreate an executable file and run it to check whether the running result is consistent with your guess. If you do not know how to compile, refer to the following three articles:
Compiler usage
Install and use the compiler Dev-C ++
Dev-C ++ download

Next, I will explain this program in two steps. Step 1:SummaryThat is, to briefly explain the meaning of each line of code in the program, to help you have a general understanding of this program. Step 2:Detailed descriptionThat is, each line of code in the program is explained in detail to deepen your understanding.

I. Summary
# Include<Stdio. h> <-Include another file
This line of code commandHeader file(. HFile)Stdio. hContent inIncludeTo our
Program. Stdio. h is in C LanguageStandard header fileOne.
Yes. To usePrintfThe function should contain this header file. By the way,StdioRepresentative
Standard input/output, That isStandard Input and Output.

Int main (void) <-function Header
C program consists of one or moreFunction. Our program has only one function:MainFunction.
Parentheses ()Indicates that main is a function;IntIndicates that the main function returns an integer;VoidIndicates
The main function does not accept any parameters. Note that int main (void) isISO/ANSI C
One of the main function definition methods defined in the standard.

/* A simple program */<-Comment
/* And */are used to performNoteTo help readers better understand the program. Compiler
Content Between/* and */(including/* and */) is ignored, and they are not compiled.

{<-Start of the function body
ThisOpen Large arc {MarkingFunction bodyStart. Function bodyClose Large arc}End. In {And}
BetweenStatementAll belong to this function.

Int num; <-declare and define the variable num
This statement indicates thatStatementAndDefinitionAVariable. Int indicates that this variable is
Integer variable.

Num = 1; <-value assignment statement
This statement setsAssignmentGive the variable num. After executing this statement, the value of num is equal to 1.

Printf ("This is a simple C program. \ n"); <-function call statement
PrintfThe function is in C language.Functions in the standard function library. This statementCallThe printf function
"This is a simple C program." is displayed on the screen, with a line break.\ NYesLine Break, It prompts
Printf starts a new line, that isCursorThe beginning of the next row. If the preceding statement does not contain
\ N, it won't wrap, and the cursor will follow "This is a simple program.

Printf ("My favorite number is % d because it is first. \ n", num );
% DTells printf to replace % d With the num value and display the num value in integer form.
Because the value of num is 1, this statement displays"My favorite number is 1
Because it is first.
And line feed.

Return 0; <-return Statement
C program shouldReturnA numeric value is used to call the media. 0 indicates that the program exits without error,
1 indicates an error occurred while running the program and exited.

} <-End of the function body
Function bodyClose Large arc}End.

Ii. Detailed Description
Now, let's further understand the meaning of each line of code. The following content is veryBasicAndImportant,
RequiredUnderstanding, FirmlyMaster.

1.# IncludePreprocessing commandsAndHeader file
When the compiler writesSource programBefore compilation,Pre-processorWill write to usSource code
Perform necessary processing, calledPreprocessing. # Include isPreprocessing commandsIt command Preprocessor
The preprocessing is:Include specific header files into our source code.
# Include<Stdio. h> The function is to include the content in the header file stdio. h into our program,
The result is that the content in stdio. h is inserted without missing a word # include<Stdio. h> The
And delete # include<Stdio. h> . In other words, it is replaced with the content in stdio. h.
# Include<Stdio. h> . This process is completed in the preprocessing phase. C-language
Mechanism for multiple programsShareThe same information provides great convenience.
Stdio. h is the header file defined in the C language standard. It containsInput and Output Functions.
All C compilers should have this header file. This isANSI/ISO CAs specified in the standard. Of course,
ANSI/iso c requires that the compiler provide more than one header file. The standards also stipulate many
Other header files will be learned later.
Some programs need to contain stdio. h, while others do not. If our program does not use printf
Function, you do not need to include stdio. h.
The header file contains the information required by the compiler for compilation. The header file may indicate the function name and
Function call method, butImplementation CodeNot in the header file, but inPre-compileOkay.
Library files.
LinkerFind the Code required by our program in the library file, and compare the Code with the code we wrote.
ProgramLinkTo link the program I wroteExecutable files. In a word, the header file is used for guidance
The compiler correctly compiles the source program we wrote into an executable file.

2.Main Function
In C, the main function isMain Function. Every C program hasThere must be and only one
Main function (main function )! The C program starts to run from the main function and ends in the main function.
Int is the main functionReturn Value TypeIt indicates that the main function should return an integer to the program
Active (such as the operating system ).
For more information about the main function, click the following link:
C/C ++ misunderstanding 1: void main

3.Note
/* A simple program */
/**/Note. Properly annotate the program to help readers (including yourself)
The code you write is faster and better understood. Annotations can be written anywhere in the source program. /* And */
Any content (including/* and */) will be ignored by the compiler. Note:/and * must be close together,
There cannot be spaces between them.
/* I am a comment */
/* I am
Cross-line comment */
/*
I also comment
*/
The preceding annotations are valid, but the following annotations are invalid because they are not written.Annotation end mark*/.
/* Invalid. No end comment mark
The following comment may surprise you:
/* I amAnnotation start mark
/* Oh, I'm not marking the start of the annotation.
I am the end annotation mark, IMatch with the first /*Instead of matching the second. */
In the above comment,Annotation end mark */matches with the first /*, Content between them
Are considered as comments.

C99Added another annotation method, which uses //Annotator, And //
In the same row, and the content on the // right is treated as a comment. No space is allowed between/AND.
// I am a comment
Int rigue; // The comment here is also valid
The above comment is valid in C99,C89Is invalid. That is to say, the old
The compiler may not support the // annotator.VC6Supported //,TC2Not supported.

4.Braces and function bodies
In C, all functions are in the upper arc ({})Identifier. Function body from open Large arc {
Start and end with closed Large arc. In subsequent tutorials, I will explain the functions in more detail.

5.Int num;
This statementStatementAndDefinitionNowVariableNum. TheSemicolon(;) Indicates this line
IsStatement.; It is a part of the statement, and a separate statement. It is also a legal C statement.
Int IsKeywordsIt represents a basic data type in C: integer.
Keyword is languageReserved WordsAnd cannot be used for other purposes. For example, we cannot use keywords for variable names or
Function name.
IdentifierIs the name of a variable or function. In this statement, num is the identifier.
In C, all variables must be declared before use. In C89, the variable Declaration must be in
Function bodyOrProgram block. For example:
Int main (void)/* C89 */
{/* Function body start */
Int doors;
Int dogs;
Doors = 5;
Dogs = 3;
{/* Start of the program block */
Int dig;
Int dug;
Dig = 6;
Dug = 8;
}/* Block end */

Return 0;
}/* Function body end */
In C99, the Declaration can be located anywhere in the function body or block. However, the variable is still
It must be declared before use. For example:
Int main (void)/* C99 */
{/* Function body start */
Int doors;
Doors = 5;
{/* Start of the program block */
Int dig;
Dig = 6;
Int dug;
Dug = 8;
}/* Block end */
Int dogs;
Dogs = 3;

Return 0;
}/* Function body end */
The above program is valid in C99, but it is illegal in C89. Currently supports C99
There are not many compilers, so your compiler may not compile the above Code. Therefore, in order to make our
Good CodePortability, We should try to use as little as possible, or even remove the new features in C99.

6.Assignment
Num = 1;
AssignmentIs a basic operation in C language. The preceding statement isAssignment Statement, Its meaning
Yes: Assign 1 to the variable num. After the value assignment operation is complete, the value of num is equal to 1.

7.Printf function
Printf ("This is a simple C program. \ n ");
Printf ("My favorite number is % d because it is first. \ n", num );
Both lines of code call the printf function. Printf isStandard C functionsThat is to say,
It is a C LanguageStandard function libraryFunction defined in. Parentheses () indicate that printf is a function,
The content in the parentheses isTransferTo the printf function. For example, in the first line of code above
Simple C program. \ n "(not including double quotation marks) is passed to the printf function, and then
The function displays the information on the monitor.\ NYesLine BreakIt prompts printf to start a new row.
Because \ n is a line break, \ n is not displayed, but a line break. If the preceding statement
If \ n is not specified, no line feed will be generated.
In the second line of the code above% DTells printf to replace % d With the num value and
Integer formDisplays the value of num.
% D is calledPlaceholderIt tells printf where to display the num value. % Used
Remind printf to display the value of a variable here (num value in this example); d tells printf
DecimalThe value of num is displayed as an integer.

8. return (return) Statement
Return 0;
ThisReturn StatementIs the last statement in our program. Int in int main (void)
Indicates that the main function should return an integer, so we need to use the return statement to return an integer.
For more information aboutReturn ValueClick the following link to viewPoint 4.
C/C ++ misunderstanding 1: void main

Some of the content you mentioned aboveNot quite understood yet,Don't be afraid, FirmlyRemember them, And thenContinue to learnRight! As learning goes deeperGradually understand. At this stage, this concept is enough.

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.