Understand the truth of the simplest C language code, "hello world!"

How to write the simplest program that can run

int main(){
}

Use the editor you are used to, create test.cpp, type these codes in, this is a program,

It can be compiled into a test.exe, which is an executable program, but this program does nothing.

You don't need to understand why this int is here, why main is needed, why there is another bracket, and why there is another brace. These may actually be irrelevant things for the time being.

The key to this main program

{Add the code and operation in this curly bracket }

The point is, you can write in curly braces what you want to do, such as:

int main(){
    让你的电脑打开某个文件的代码
    让你的电脑关机的代码
}

Write these codes in, compile the program test.exe, you execute it, it will open a certain file , and then shut down your computer

Hello world!

#include <stdio.h>
int main() {
    int x = 100;
    printf("%s", x);
    return 0;
}

We have seen that almost all tutorials will teach you to write this hello world, and there are several puzzling problems in it. I would like to try to explain it through another case:

  • printf("%s", x); Why is there this %s in printf("%s ", why is it put in "" , why is there another x here

  • Why write a statement like this, with a strange parenthesis followed by a strange semicolon ?

  • Why is there a return 0 at the end , which is the return value, where to return, and what to do after returning?

  • Why did you write another #include <stdio.h> at the beginning ?

These are the contents that must be understood when learning programming, but we can first focus on truly understanding hello world;

Translated into the above case:

导入stdio.h文件里面的代码
int main() {
    在屏幕上打印 hello world 的代码
}

Translated into this, you will find that we have done two things, import and print, you can simply remember these two rules first:

  • The import is placed outside the main or something

  • The executed code is placed in the main pile

Another wording?

The above is the writing method of C language. Next, I will introduce the writing method of C++. Don’t worry, the difference between C language and C++ is not difficult for us. On the contrary, it just changes some special attributes. We use C ++ Write the same code:

#include <iostream>
using namespace std;

int main(){
    cout << "Hello world!";
}

That's right, the above include and using still function as an import code;

And cout<< "XXXX" is the code to print some words (or other things) on the screen;

Why is there no return? It is not necessary here, we can discuss it in detail in the function section.

practice your code

The best way to improve is to keep writing code, play through the above code, and see what happens when you make some changes!

Guess you like

Origin blog.csdn.net/Littlelumos/article/details/129567248