[Quick start of C language] Take you to understand C language, get started with zero basics①

foreword

This is the blogger’s first learning blog. The content written will definitely have shortcomings. I hope readers can bear with it and understand it. I also hope that you can point out the problems in time after reading, and the author will definitely actively adopt suggestions. Continuous improvement, continuous progress. Thank you for your corrections.

The content of this article is mainly about some basic knowledge of C language. After reading, everyone can have a general understanding of C language. Of course, each knowledge point is a simple understanding. In the future, bloggers will follow the C language learning order to give detailed explanations. The length is long, it is recommended to collect and eat.

This C language learning series, I will continue to do it, please continue to pay attention to the bloggers, your support and encouragement are the biggest motivation for my update! !

Table of contents

1. Beginning with C language

1.1 What is C language

1.2 Reasons to learn C language

1.2.1 Design Features

1.2.2 Efficiency

1.2.3 Portability

1.2.4 Powerful and flexible

1.2.5 For Programmers

2. The first C language program

2.1 main function

2.2 Library functions

2.2.1 printf function

3. Data Type

3.1 char type

3.2 int type

3.3 long, long long type

3.4 short type

3.5 float, double type

4. Constants and Variables

4.1 Variables

4.1.1 How to define variables

4.1.2 Classification of variables

4.1.3 Use of variables

4.1.4 Scope and lifetime of variables

4.2 Constants

4.2.1 Literal Constants

4.2.2 const-modified constant variables

4.2.3 Identifier constants defined by define

4.2.4 Enumeration Constants

5. Strings, escape characters, comments

5.1 Strings

5.2 Escape characters

5.3 Notes

Conclusion

1. Introduction to C language

1.1 What is the C language

C language is a general-purpose computer programming language that is widely used in low-level development. The design goal of the C language is to provide a programming language that can be compiled in an easy way, handle low-level memory, generate a small amount of machine code, and run without any runtime support. And maintains good cross-platform characteristics, C language programs written in a standard specification can be compiled on many computer platforms. Simply put, C is the programming language that people use to communicate with computers.

1.2 Reasons to learn C language

Over the past many years, C has become one of the most important and popular programming languages. C produces all things, C language is the mother language, and it is the bridge between human-computer interaction and the bottom layer. In the past 50 years, in the [TIOBE] rankings, C/C++ has been occupying the top three positions for a long time, and it has not been shaken. In the process of learning the C language, you can find its many advantages. Below, we introduce some of the more prominent points.

1.2.1 Design Features

C is a popular language that combines the control properties of computer science theory and practice. The design philosophy of the C language allows users to easily complete top-down planning, structured programming, and modular design. Therefore, programs written in C language are easier to understand and more reliable.

1.2.2 Efficiency

C is the language of colleges and universities. C language makes full use of the advantages of current computers, so C language is relatively more compact and runs very fast.

1.2.3 Portability

C is a portable language. This means that C programs written on one system can run on other systems with little or no modification.

1.2.4 Powerful and flexible

The C language is powerful and flexible. C programs can be used to solve problems in physics and engineering, and even to animate special effects for movies.

1.2.5 For Programmers

The C language was designed to meet the needs of programmers who use C to access hardware and manipulate bits in memory. The C language has a rich set of operators that allow programmers to express their intentions concisely. Also, most C implementations have a large library of many useful C functions. These functions are used to deal with problems that programmers often need to solve.

2. The first C language program

//Write a simple code 
//output hello world on the screen 
# include  <stdio.h> //Header file

int  main ()                      // main function
 {
     printf ( "hello world\n" );    // use printf function to print hello world

    return  0 ;                   // at the end of the main function, return a value 
}

In this simple C language program, there are two important functions that need your attention

2.1 main function

The main function is used as the entry point of the program, and there is only one in a project. It means that if there are multiple files in a project, there can only be one main function.

2.2 Library functions

The library function is provided by the C language itself, and it needs to be referenced when using it. The reference format is #include . In the above program, we use the printf function, and its corresponding library function is stdio.h(standard input output.header). Refer to this header file, you can use this function. In the future learning process, we will encounter many library functions, and library functions are equally important in the learning of C language.

Next, let’s take a closer look at the printf function.

2.2.1 The printf function

The function of the printf function is to output data in a specific format to the screen. If there is no format, it will be printed as it is. Different control characters are required to print different data.

     control character                                         output form
        %d                     Output as actual length of decimal integer data
        %ld                                          output long integer data
        %c                                 used to output a single character
        %f                              Used to output single-precision floating-point numbers
        %lf                              Used to output double precision floating point numbers
        %s                                 to output a string
        %x                                     output integer in hexadecimal

3. Data Types

Before talking about data types, you should understand the storage unit in a computer. A byte is the memory unit of a computer. The computer uses binary, which is composed of numbers 0 and 1 (usually, decimal is used in real life, which is composed of numbers 0~9). When storing a binary 0 or 1, it will occupy 1bite (bit) of memory space, 1Byte (byte) = 8bite, 1KB = 1024byte, 1MB = 1024KB, 1GB = 1024MB, and so on, there are TB, PB, etc.

In a computer, data is stored in a storage unit, which consists of a finite number of bytes. The range of data stored in each storage unit is limited, and it is impossible to store infinite numbers or infinite recurring decimals. C language provides many data types, why is one type not enough? Because the C language lets the programmer choose different types for different situations. Can describe integers, decimals, single characters, or strings. This has a variety of data types. Different data types occupy different sizes in the computer memory space. Common data types are as follows.

3.1 char type

The char type is a character data type, generally used to store characters (such as letters or punctuation).

char ch = 'w';
char grade = 'A';

3.2 int type

The int type is a signed integer, that is, the value of the int type must be an integer, which can be a positive integer, a negative integer, or zero. Its value range varies depending on the computer system.

int a = 0;
int grade = 100;

3.3 long, long long type

Typically, numbers used in program code, such as 2345, are stored as int types. If using a large number such as 1000000000 exceeds the range that the int type can represent, the long type is usually used to define the integer type. If it is not large enough, the long long type is used to define the integer type. It is essentially an integer, and its value must be an integer.

int age = 18 ;
 float weight = 78.5 ;
 char ch = 'p' ;
 //type + variable name + value

3.4 short type

The short type is the opposite of the long type and is used to store some smaller integers.

3.5 float, double type

There are various integer types (int, long, long long) in the C language, and floating-point types are also indispensable. Floating-point numbers are often used in financial and digital-oriented programs. Common floating-point types in C language include float and double types. Floating-point types can represent a larger range of numbers including decimals.

The C standard stipulates that the float type must be able to represent at least 6 significant digits, which means that the float type must be able to represent the first 6 digits of 33.333333, not accurate to 6 digits after the decimal point.

Another floating-point type provided by the C language is double (meaning double precision). The minimum value range of the double type and the float type is the same, but must be able to represent at least 10 significant digits.

#include <stdio.h>

int a = 100 ;          //global variable

int  main ()
 {
     int b = 10 ;       //local variable     

    return 0;
}

4. Constants and Variables

Many values ​​in life are constant (such as: pi, gender, ID number, blood type, etc.), and many values ​​are variable (such as age, weight, salary, etc.). In the C language, constants are used to represent immutable values, and variables are used to represent variable values.

4.1 Variables

In the process of programming, the use of variables is very extensive, such as formulas such as x = 5 in mathematics, x is a variable, and the value of x can be changed. A variable is a quantity whose value can be changed while a program is running.

4.1.1 How to define variables

A variable is an identifier or a name. When naming a variable, it should be known by name to facilitate communication and maintenance.

There are 3 basic elements of a variable: variable name, type and value.

The variables of C language mainly appear in the form of variable names in the program. The naming rules are as follows:

(1) Consists of letters, numbers and underscores, and the first character of the variable can only be letters or underscores. Such as add, sum, average, score, math.

(2) The C language coding system regards uppercase letters and lowercase letters as different characters, that is, uppercase letters and lowercase letters are two different variables.

(3) The principle of naming is generally to know the meaning of the name and make it easy to read. Such as int sum and float average, it can be easily seen that sum may represent the sum, and average may represent the average.

(4) Variables should be defined before use. Only if it is defined first, the compiler can recognize the variable when it encounters it in the program.

#include <stdio.h>

int main()
{
    int num1 = 0;
    int num2 = 0;
    int sum = 0;

    printf ( "Enter two operands:" );
     scanf ( "%d %d" , &num1, &num2); //scanf function input function

    sum = num1 + num2; // sum 
    printf ( "sum = %d\n" , sum);

    return 0;
}

4.1.2 Classification of variables

Variables can be divided into local variables and global variables, which I will demonstrate with a piece of code below.

#include <stdio.h>

enum Sex //Define enum constants
{
    MALE,
    FEMALE,
    SECRET
};
//MALE, FEMALE, SECRET in parentheses are enumeration constants

int  main ()
 {
     //literal constant demo 
    3.14 ; //literal constant 
    1000 ; //literal constant

    //const-modified constant variable 
    const  float pi = 3.14 ; //here pi is a const-modified constant variable 
    pi = 5.14 ; //Error, const-modified constant variables cannot be modified directly!

    //#define the defined identifier constant 
    # define MAX 100 
    printf ( "MAX = %d\n" , MAX);

    // Demonstration of enum constants 
    printf ( "%d\n" , MALE);
     printf ( "%d\n" , FEMALE);
     printf ( "%d\n" , SECRET);

    return 0;
}

{} is a code block. Simply put, variables defined inside a code block are local variables, and variables defined outside a code block are global variables.

When two variables have the same name, local variables take precedence over global variables. As shown below.

As you can see, local variables are printed first. So when a local variable and a global variable have the same name, the local variable takes precedence.

4.1.3 Use of variables

When a variable is used, it is only necessary to write the variable directly in the expression, and the variable will participate in the calculation of the expression. Variables in C language

In the program mainly in the form of variable names. The following uses a summation program to demonstrate the use of variables.

#include <stdio.h>

int main()
{
    printf("c:\code\test.c");

    return 0;
}

4.1.4 Scope and lifetime of variables

(1) Scope

Scope is a programming concept, in general, a name used in a piece of program code is not always valid/available, and the scope of code that qualifies the availability of the name is the scope of the name.

That is, the scope of a local variable is the local scope where the variable is located, while the scope of a global variable is the entire project.

(2) Life cycle

The life cycle of a variable refers to the period between the creation of the variable and the destruction of the variable, like the beginning and the end of a thing.

The life cycle of a local variable is: entering the scope, the life cycle begins; out of the scope, the life cycle ends.

The life cycle of global variables is: the life cycle of the entire program.

4.2 Constants

Quantities whose values ​​cannot be changed while the program is running are called constants. For example, x = 5 + 8; “5” and “8” in the statement, such data are fixed during program execution and do not change. Constants in C language are usually divided into the following four types.

#include <stdio.h>

int Add(int x, int y)
{
    return x + y;
}

/*C language style comments
int sub(int x, int y)
{
    return x - y;
}
*/

int  main ()
 {
     //C++ comment style 
    //int a = 10; 
    //Call the Add function to complete the addition 
    int a = 10 ;
     printf ( "%d\n" , Add( 1 , 2 ));

    return 0;
}

4.2.1 Literal Constants

Literal constants are the most common constants in the C language, such as 3.14, 500, ‘a’, ‘b’

4.2.2 const-modified constant variables

Const is a keyword in the C language, and the variable modified by const will have some kind of constant attribute – it can only be read, but not modified. But it is still a variable in essence, but it has constant properties, so it is called a constant variable.

4.2.3 Identifier constants defined by define

Compared with const-modified constant variables, define defines a serious constant.

The definition method is #define name data. After the definition, the defined identifier constants can be used directly in the program.

4.2.4 Enumeration Constants

When some data needs to be enumerated one by one, enumeration constants can be created to represent them, which are consistent with the identifier constants defined by define, and can be directly quoted when using.

As the above print result, the default enumeration constant starts from 0 and increases by 1 in turn.

5. Strings, escape characters, comments

5.1 Strings

“Hello my friend!”

This string of characters enclosed in double quotes is called a string literal, or simply a string. Double quotes are not part of the string, double quotes only tell the compiler that it encloses a string.

The end mark of the string is an escape character of \0. When calculating the length of the string, \0 is the end mark, not counted as the content of the string.

The above code is to put the string into a character array (the definition of the array will be explained by subsequent bloggers).         

Seeing the running result of this code, readers should roughly understand the function of \ 0. \0 is used as the end marker of the length of the string. If the end of \ 0 is not added to the array defined by yourself, printf will randomly print it until it encounters \0, then it will stop. So in the process of creating an array, when putting the characters in the string into the array one by one, remember to add a \0 at the end.

Let’s look at another piece of code.

As shown in the figure, we did not add \0 at the end of the array, the printed name is correct, why is this? There is nothing to add the end sign, and the printing has stopped? The reason is that when there is space left in the character type array, \0 will be automatically stored at the end. You see, computers can actually handle these details themselves.

Why do the two functions print out different results? This shows the existence of \ 0 from the side. When sizeof calculates the space size \ 0 takes up an extra byte of space, and strlen essentially calculates the number of characters before \ 0.

5.2 Escape characters

Escape characters are special character constants. An escape character begins with a backslash “\”, which can be followed by one or more characters. The escape character is different from the original meaning of the character and has a special meaning, so it is called an escape character.

If we want to print a directory on the screen: c:\code\test.c, how should we write the code?

#include <stdio.h>

int main()
{
    printf("c:\code\test.c");

    return 0;
}

As expected, we want to get c:\code\test.c, in fact, the result of running the program is like this:

Here we have to mention escape characters. The escape character, as the name suggests, is to change the meaning. Let’s look at some escape characters below.

escape character Paraphrase
\? Used when writing multiple hellos in a row to prevent them from being parsed as three-letter words (not commonly used)
\’ Used to represent the character constant ‘ (single quote)
\” double quotes used to denote a string
\\ Used to represent a backslash, preventing it from being interpreted as an escape sequence
\a Warning character, beep (ringing)
\b Backspace, move the current position to the previous column
\f Feed stop, move the current position to the beginning of the next page
\n newline, move the current position to the beginning of the next line
\r Enter to move the current position to the beginning of the line
\t Horizontal tab character, same function as the tab key
\v vertical tab
\ddd ddd represents 1~3 octal digits
\xdd dd means 2 hexadecimal digits

Let’s go back to the beginning, so how to print c:\code\test.c on the screen? No nonsense, go directly to the picture.

You see, once you master the escape characters, you can easily type a full directory.

5.3 Notes

Comments are also essential in the process of learning C language, including using C language in the future. I believe that careful readers can also find that comments are added in some codes of bloggers, so what is the use of comments?

(1) Unnecessary code in the code can be deleted directly or commented out.

(2) Some codes in the code are more difficult to understand. You can add a comment text. Imagine when you have worked so hard to write the code, others can’t understand it at all, so what’s the use?        

Next, we explain two annotation styles:

C-style comments:  /xxxxxxxxxxxxxxxxxxxxx/

C++ style comments: //xxxxxxxxxxxxxxx

Note: C language style comments cannot nest comments, while C++ style comments can be one line or multiple lines. Bloggers recommend using C++ style comments.

Let’s take a look at the effect of the two annotation methods.

#include <stdio.h>

int Add(int x, int y)
{
    return x + y;
}

/*C language style comments
int sub(int x, int y)
{
    return x - y;
}
*/

int  main ()
 {
     //C++ comment style 
    //int a = 10; 
    //Call the Add function to complete the addition 
    int a = 10 ;
     printf ( "%d\n" , Add( 1 , 2 ));

    return 0;
}

Conclusion

Thank you for your patient reading, the blogger is a freshman and still has a lot to learn. Writing this article is based on what I have learned, and I will continue to update my learning records in the future. We will work hard to improve and become excellent. A little rookie can also have big dreams. Follow me and we will learn together.

In the series “Introduction to C Language”, I will divide it into two or three articles according to the length. See you in the next issue.

Leave a Comment

Your email address will not be published. Required fields are marked *