当前位置:网站首页>The first C language program (starting from Hello World)
The first C language program (starting from Hello World)
2022-07-25 11:44:00 【It takes time for fish to find water】
There is a conventional habit among programmers , When we learn any programming language , The first program written , Is to print a line of characters on the display “Hello World”.
Where does this habit come from , First review C The history of language , You can learn the origin of this habit .
1972 year ,C Language from Dennis Ritchie And colleagues at Bell Laboratories . Then ,C The designer of language Dennis Ritchie And famous computer scientists Brian W. Kernighan, Co authored an introduction C Language and its programming methods of the authoritative classic works ——《The C Programming Language》.
The first example program in the book , Is to output a string of characters on the screen “Hello World”.
so far , Many programming language textbooks also follow this habit . therefore , If you have seen Java,PHP,Go And other programming languages , You will find that their first example program is also “Hello World”.
It can be seen that everyone still recognizes this habit , And has continued this tradition in his own works .
Although no one can scientifically explain why Hello World So popular , however ,Hello World Programs have indeed become a milestone in the history of computer development .
Environmental preparation :C Language development environment installation
Sample code :
#include <stdio.h> int main(){ printf("Hello World"); return 0; }
The effect of the sample code : The effect of this program is very simple , Is to output a line of characters on the screen "Hello World".
1. The main function
First , The main function main , A standard main function is as follows :
int main() // This is the main function
{
return 0; // The return value of the main function
}
main stay C The language represents a main function .
After the double slash is notes , Generally speaking , Comments are used to mark the purpose of this code or explain ideas . Because comments are not compiled as code , So no matter what comments are added , Will not have any impact on the actual operation of the code .
2. What is a function ?
In the field of Mathematics function , And... In programming languages function Completely different .
In programming languages , You can think of a function as a box , This box has the following features :
- At the beginning of execution , Function can be input with some values
- In the process of execution , Functions can do some things
- After execution , Function can return some values
Take the example code above as an example to explain :
- The main function has no input (
main(): The input parameter is null ) - The main function prints a line of words onto the screen (
printf("Hello World");) - The main function returns 0(
return 0;)
among , int Indicates the return type For integer type , int yes integer( Integers ) Abbreviation . This is stipulated by the language standard , You can't write other words .
main yes Function name , main The brackets that follow () Inside is the input parameter , It is currently empty .return Followed by a function Return value , by 0. and 0 It's an integer , And before the function name int Corresponding .
Sum up the formula of function :
Function return value type Function name ( Function input parameter value ) { Do something return Function return value ; }
What is enclosed by curly braces is called The body of the function , Note that the function body must be included by curly braces and cannot be omitted . Function name above curly braces 、 Function parameters and return values are called Function header .
3. Write your own function
demand : According to the above formula of function writing , Write a function that adds two integers . This function needs to do : Enter two integers , Return the result of their addition .
Since this function is used to calculate addition , We name the function add . Of course, the function name of the custom function can be written according to your preferences , Even if it's written as aaaaa It's OK . however , Have for function name semantic , It is convenient for people to read and understand , We usually use English as the function name .
// This piece of code is called add Function definition of function
int add(int a, int b) {
return a + b;
}
explain : Define a return value as int type ( integer ) Function of , The function is called add, The input value is : Integers a and Integers b,
Return value : Returns the sum of two integers , Both addends are integers , So the result is also an integer .
This piece of code is called add function Function definition of .
4. The main function is the whole C The entrance to language programs
add function It can run directly ? The answer is No good .
be-all C Language codes have a starting entry , And this entrance is The main function main . After entering the main function , To call other functions through the main function .
It also means that , Every C The language code , There can only be one main function .
Slightly modified code :
#include <stdio.h> int add(int a, int b) { return a + b; } int main() { int result; result = add(2, 3); printf("%d", result); return 0; }
When the program is running , First of all The main function main . Then call what we just wrote add function 了 . We passed on 2 The values are integers 2 and 3 to add function .
The definition of the function specifies the need to pass a、b,2 Parameters , When we call , It must also be passed on 2 individual , And the type also needs to be consistent as far as possible , Otherwise, the compilation may report errors .( If the type is different , The compiler will try automatic type conversion . If automatic type conversion fails, compilation fails .)

problem : Who called the main function ? The return value of the main function must be int Do you ?
answer : The main function is called automatically at the beginning of the program , There is no need to actively call the main function in the program . The return value of the main function will be returned to the program calling this program .
C The language standard stipulates that the main function has a return value and must be int . If the program ends normally , Generally, the return value is set to 0.
5. To call a function , You must know the function first
The compiler starts with code , Read the code from top to bottom .
The compiler first sees the definition of a function , Describes a man called add Function of . next , stay main Required in add , Because the compiler already knows add The definition of , Therefore, the compiler can compile normally .(ps: First define , After use )
What happens if you reverse the definition of functions and the order of function calls ?
First , The compiler sees add The name , The compiler will be confused , add What is it? ? The compiler cannot understand add What is it . therefore , The compiler will report an error , And stop compiling .

6. What is a variable ?
stay add function After the calculation , There needs to be something to accept add The returned value . therefore , We are add The previous statement states that int integer Of Variable .
What are variables ? You can think of it as an empty box , It can contain any other value consistent with its type .
result It's just a name we gave it , Of course , You can call it anything . For example he, It's called xiangzi, Fine (ps: Naming should be semantic ).
We put add Back home 5, Put in result . therefore , result The value inside is 5 了 .
= Equal sign , stay C In language is Assignment operator , It has the function of loading the value on the right into the variable on the left . Like a function , The equal sign here is the same as that in Mathematics , It's also very different , It doesn't mean equal .
Assignment operator : The value to the right of the symbol , An operator that puts variables on the left .
The example written above is add function Accept 2,3 For input , return 5, Assigned number = Assign a value to result The process of .
Can you write it like this ? Get rid of int result; This article .
int main() {
result = add(2, 3);
printf("%d", result);
return 0;
}
The answer is No , Variables must be declared before using .
The compiler sees result The name , But never seen result The definition of , You will certainly wonder what kind of variable it is , It may even be a function instead of a variable . such , Unfortunately, the compiler can only give a hint of compilation errors , And end the compilation .
int result;It must be like this , Declare a variable , Name is
result, The type isint. Next , The editor can write downresultFor oneintVariable of type . In the following code , You can use this happilyresultThe variable .
7. identifier
In the previous code , Named by ourselves , The name used to refer to an entity , for example :add,result, The parameters of the function a,b It's all one identifier .
The identifier is a special identifier named by ourselves , Used to represent a variable 、 The name of a function or other entity .
for example : Our custom function is named add It is to clearly indicate the intention of the function . And name the variable result, It is also to show that what is stored in the variable is The result returned by the function .
also , To enable the compiler to recognize identifiers , Must be declared or defined . for example ,add Is defined as a function ,result, a,b It is declared as an integer variable . If the compiler encounters an undefined or undeclared identifier , You will not be able to understand the specific name of this identifier and report an error .
stay C In language , The identifier can be named as you like , But the following rules must be followed :
Identifiers can be in lowercase letters 、 Capital 、 Numbers and underscores to name . however , The first character of the identifier must be a letter or an underline , Not Numbers . also , Identifiers are case sensitive .
8. key word
problem :int It's a identifier Do you ?
answer : No . First int We didn't name it casually , secondly int Not the name of any entity .
int yes C One of the languages key word .
key word It is stipulated in the language standard , And it has special significance and use in the code . therefore , Keywords cannot be used as identifiers .
C The keywords in the language are shown in the following table .
| auto | _Bool* | break | case |
| char | _Complex* | const | continue |
| default | restrict* | do | double |
| else | enum | extern | float |
| for | goto | if | _Imaginary* |
| inline* | int | long | register |
| return | short | signed | sizeof |
| static | struct | switch | typedef |
| union | unsigned | void | volatile |
| while |
9. What is a literal constant ?
problem : that , image 2,3, This value , Do you need to declare ?
answer : Unwanted , They are Constant , Cannot be changed . And once it's written , We already know that they are integers int Constant of type .
alike , Literal constant of string It doesn't need to be declared , for example :"Hello World". Wrapped in double quotation marks , We think it is a string , To distinguish it from the numerical value .
Variables can be changed by assignment , Constant cannot be changed , So it cannot be assigned .
2 = 3; // error
"Hello" = "World"; // error
10. printf function
#include <stdio.h>
int main(){
printf("Hello World");
return 0;
}
and add equally , printf It's also a function , But this is not a custom function , It is a function of the system .
Let's take the string literal constant "Hello World" Passed on to printf function . When running code , We saw this line on the screen
operator . obviously , printf function The function of is to output the string to the console .
printf By word print( Print ) And the words format( Format ) The first letter of f form , Meaning for Format printing .
In the early , The output of the computer mainly depends on connecting the printer to print characters on paper . Today, , Most of the output of the computer is realized on the screen . however print This word has been retained . Sometimes we use the term printing , But in fact , We output characters in the console on the screen .
printf Function more usage
int main() {
int result;
result = add(2, 3);
printf("%d", result);
return 0;
}
Compare two pieces of code , We write Hello World Time passed only 1 A parameter for printf , But why add function Later, it can be transmitted 2 Give it one ? Does the number and type of parameters defined by the function need to be consistent with that when the function is called ?
printf Is a very special function , It's a Argument function , Therefore, variable number and type of input parameters can be accepted . Here we don't need to care too much about how to write a variable parameter function , Just use it for the time being .
Through the following example , We can simply understand printf function More use of .
Used to print an integer :printf(“%d”, integer int);
printf("%d", 12345);
Used to print two integers :printf(“%d\n%d\n”, integer int1, integer int2);
// \n Means line break , Start from the next line and continue printing printf("A=%d\nB=%d\n", 123, 456);
To sum up printf Formula
printf(“XXX placeholder 1 XXX placeholder 2 XXX placeholder 3”, Replace 1, Replace 2, Replace 3);
printf The first parameter of must be character string , Here we pass in a string literal constant ( Wrapped in double quotation marks ). among , To occupy a place % Conversion operation Express . for example : integer int The placeholder for is %d . The following replacement parameters , The previous placeholders will be replaced in turn . printf Is a variable length parameter function , As long as the placeholder of the first string parameter is written correctly , Any number of replacement parameters can be added later .

11. #include command
printf function It's not the function we define , It's a function of the system . This function is written in the file stdio.h in , We're going to use printf You must first let the compiler understand printf .
Assume printf The function definition of is written in the file stdio.h in , use #include command , You can stdio.h Copy the code of into our code .
ps:stdio.h There is no definition printf function , But it has printf function Function declaration of . Beginners can understand it as stdio.h Inside , Yes printf Function definition of .
边栏推荐
猜你喜欢

What kind of product power does Hongguang miniev, the top seller of new energy, have?

Small and micro enterprise smart business card management applet

Talking about Devops monitoring, how does the team choose monitoring tools?

Leetcode sword finger offer 28. symmetric binary tree

W5500在处于TCP_Server模式下,在交换机/路由器网络中无法ping通也无法通讯。

第4章线性方程组

varest蓝图设置json

PostgreSQL stepping on the pit | error: operator does not exist: UUID = character varying

Hacker introductory tutorial (very detailed) from zero basic introduction to proficiency, it is enough to read this one.

相似矩阵,可对角化条件
随机推荐
SQL injection less23 (filter comment)
Summary of combination problems of Li Kou brush questions (backtracking)
【leetcode刷题】
WIZnet嵌入式以太网技术培训公开课(免费!!!)
Miidock Brief
活动报名 | 玩转 Kubernetes 容器服务提高班正式开营!
ArcMap cannot start the solution
Shell fourth day homework
Several common PCB surface treatment technologies!
Reflection reflection
Common linear modulation methods based on MATLAB
SQL language (6)
使用Three.js实现炫酷的赛博朋克风格3D数字地球大屏
各种控件==PYQT5
黑客入门教程(非常详细)从零基础入门到精通,看完这一篇就够了。
基于cornerstone.js的dicom医学影像查看浏览功能
Database integrity -- six constraints learning
矩阵的特征值和特征向量
Dynamic planning problem 03_ Maximum sub segment sum
Greedy problem 01_ Activity arrangement code analysis