<C language> Initial C language

1 What is the C language?

C language is a general-purpose, 面向过程computer programming language. It was developed by Dennis Ritchie at Bell Laboratories around 1972 and became a language widely used in systems programming and application development. C language has concise syntax, efficient execution speed and powerful underlying control capabilities, so it is widely used in operating systems, embedded systems, game development and other fields.

​ In the 1980s, in order to avoid differences in the C language grammar used by various developers, the US National Bureau of Standards formulated a complete set of American National Standard grammar for the C language, known as the original standard of the C language ANSI C.

C language is a 面向过程computer programming language, which is different from object-oriented programming languages ​​such as C++ and Java. Its compilers mainly include Clang, GCC, WIN-TC, SUBLIME, MSVC (VS), Turbo C, etc.

2 The first C language program

#include <stdio.h>
int main() {
    
    
    printf("Hello World\n");
    return 0;
}

explain:

  • #include <stdio.h>This line of code is a preprocessing directive that tells the compiler to include header files for standard input and output functions stdio.h. The header file contains function prototypes and constant definitions for input and output operations.
  • The main function of the program main, which is the entry point of the C language program. intIs the return type of the function, mainis the name of the function, and the empty parentheses after it indicate that the function does not accept any parameters. There must be a main function, and there can only be one.
  • A function in the C language standard library printf, which is used to output the specified format string to standard output (usually the console). Here, we are passing the string "Hello World" as an argument to printfthe function and it will print that string to the console.
  • return 0, which indicates the end of the function and returns the integer value 0 to the caller as the function's return value. In C language, a return value of 0 usually indicates that the program executed successfully.
  • \nis a special escape character called a newline. It is used to indicate a newline operation in the output, that is, to move the output cursor to the beginning of the next line.

2.1 printf function

printfIs a function in the C language standard library, which is used to format the output text to the standard output (usually the console). ``

Function prototype:

int printf(const char *format, ...);

printfThe main function of the function is to format the corresponding parameter into the specified text according to the placeholder in the format string, and output it to the standard output. The return value of the function is the number of characters printed out. Placeholders %begin with and are followed by one or more characters that specify the type of argument and the format of the output.

Common formatting placeholders and their usage are as follows:

  • %d: Output a signed decimal integer.
  • %u: Output an unsigned decimal integer.
  • %f: Output floating point number.
  • %c: Output a single character.
  • %s: output string.
  • %p: Output pointer address.
  • %xOr %X: output a hexadecimal integer.

Ordinary characters in the format string are output as-is, except for placeholders.

In printfthe function, you can set the precision, width, and padding of the output by using the formatting options. Here are some commonly used formatting options:

1. Precision (Precision): used to specify the output precision of floating point numbers or strings.

  • %.nf: Set the precision of the floating-point number after the decimal point to n digits.
  • %.*f: Specify the precision after the decimal point of the floating-point number through a variable, for example %.*f, pass an integer parameter n later to specify the value of the precision.
float pi = 3.14159;
printf("%.2f", pi);  // 输出:3.14

int precision = 3;
printf("%.*f", precision, pi);  // 输出:3.142

2. Width: It is used to specify the output field width, which can be filled with spaces or other characters.

  • %nd: Set the output width of the integer to n characters, and fill the insufficient part with spaces.
  • %*d: Specify the output width of the integer through a variable, for example %*d, pass an integer parameter n later to specify the value of the width.
int num = 42;
printf("%6d", num);  // 输出:    42

int width = 8;
printf("%*d", width, num);  // 输出:      42

3. Filling character (Padding Character): used to specify the character to fill the output field, the default is a space.

  • %nd: Add padding characters before the output width n of the integer, for example %6d, set the integer width of the output to 6 characters, and pad with spaces by default.
  • %*cd: Specify the filling character through a variable, for example %*cd, pass a character parameter c later to specify the value of the filling character.
int num = 42;
printf("%06d", num);  // 输出:000042

char fillChar = '*';
printf("%*cd", 8, fillChar, num);  // 输出:******42

2.2 scanf function

scanfis a function in the C language standard library for reading input data from standard input (usually the keyboard).

Function prototype:

int scanf(const char *format, ...);

return value:

scanfThe function returns the number of data items successfully read, or a negative number if an error occurred or the end of input was reached.

scanfAccording to the placeholders in the format string, the function reads the corresponding data from the standard input and stores it in the specified variable.

Common formatting placeholders and their usage are as follows:

  • %d: Read a signed decimal integer.
  • %u: Read an unsigned decimal integer.
  • %f: Read a floating point number.
  • %c: Read a single character.
  • %s: Read a string.
  • %p: Read pointer address.
  • %xOr %X: read a hexadecimal integer.

Except for the placeholders, ordinary characters in the formatted string will be matched with the input data, and corresponding characters need to be input to match successfully.

scanfThe function takes input according to the format string and the corresponding parameters, if the input data does not match the placeholders in the format string, it may cause input errors or run-time errors. Therefore, when using scanfthe function, you need to ensure that the format string and parameters match correctly to avoid potential problems.

int main() {
    
    
    int num;
    printf("Enter a number: ");
    scanf("%d", &num);   //输入3
    printf("You entered: %d\n", num);  //打印: You entered 3  
    return 0;
}

3 basic data types

char     //字符数据类型
short    //短整型
int      //整形
long     //长整型
long long//更长的整形
float    //单精度浮点数
double   //双精度浮点数

//类型的使用:
char ch = 'w';
int weight = 120;
int salary = 20000;

The size of the data type depends on the compiler and target platform implementation. The compiler determines the sizes of different data types according to the C language standard specification and the characteristics of the target platform.

printf("%zu\n", sizeof(char));       //1
printf("%zu\n", sizeof(short));      //2
printf("%zu\n", sizeof(int));        //4
printf("%zu\n", sizeof(long));       //4
printf("%zu\n", sizeof(long long));  //8
printf("%zu\n", sizeof(float));      //4
printf("%zu\n", sizeof(double));     //8
printf("%zu\n", sizeof(long double));//8/16

4 variables, constants

Some values ​​in life are constant (for example: pi, gender, ID number, blood type, etc.)

Some values ​​are variable (eg: age, weight, salary).

Variables are identifiers used to store and manipulate variable data. In a program, we can declare a variable and allocate memory space for it, and then we can refer to and modify the value stored in memory through the variable name. The value of a variable can change during program execution.

Constants are fixed values ​​that cannot be changed. In programs, we can use constants to represent unchanging values ​​such as numbers, characters, or strings. The value of a constant is determined when it is defined and cannot be modified.

  • Variables are used to store and manipulate mutable data whose value can change during program execution.
  • A constant is used to represent an unchangeable fixed value whose value is determined at definition time and can no longer be modified.

4.1 Method of defining variables

int age = 150;
float weight = 45.5f;
char ch = 'w';

4.2 Naming of variables

  • Can only consist of letters (both uppercase and lowercase), numbers, and underscores ( _ ).
  • Cannot start with a number.
  • Cannot exceed 63 characters in length.
  • Variable names are case sensitive.
  • Variable names cannot use keywords.

4.3 Classification of variables

  • local variable
  • global variable
#include <stdio.h>
int global = 2019;//全局变量
int main() {
    
    
    int local = 2018;//局部变量
    //下面定义的global会不会有问题?
    int global = 2020;              //局部变量
    printf("global = %d\n", global);//global = 2020
    return 0;
}

There is actually nothing wrong with the definition of the local variable global variable above!

When a local variable has the same name as a global variable, the local variable takes precedence.

Use of variables:

#include <stdio.h>
int main() {
    
    
    int num1 = 0;
    int num2 = 0;
    int sum = 0;
    printf("输入两个操作数:>");
    scanf("%d %d", &num1, &num2);  //键盘输入: 3 5
    sum = num1 + num2;
    printf("sum = %d\n", sum);  //sum = 8
    return 0;
}

4.4 The scope and life cycle of variables

In C language, variable scope (scope) and lifetime (lifetime) are concepts that describe the visibility and existence time of variables in the program.

Scope (Scope) refers to the visible range of variables in the program. Variables have different accessibility in different scopes. There are several scopes in C language:

  • Block Scope : A variable is declared within a code block (surrounded by curly braces {}) and is visible inside that block. Once you leave the block, the variable goes out of its scope.

    int main() {
          
          
        int x = 10;
        {
          
          
            int y = 20;
            printf("%d\n", x);  // 可以访问外部块中的变量
            printf("%d\n", y);  // 可以访问内部块中的变量
        }
        printf("%d\n", x);  // 可以继续访问外部块中的变量
        // printf("%d\n", y);  // 错误!超出了变量 y 的作用域
        return 0;
    }
    
  • Function Scope : Variables are declared inside a function and are visible throughout the function. Function parameters and variables declared inside functions have function scope.

    int sum(int a, int b) {
          
          
        int result = a + b;
        return result;
    }
    
    int main() {
          
          
        int x = 10;
        int y = 20;
        int total = sum(x, y);
        printf("%d\n", total);
        // printf("%d\n", result);  // 错误!超出了变量 result 的作用域
        return 0;
    }
    
  • File scope (global scope) (File Scope) : Variables are declared throughout the source file and can be accessed by any function in the file. Variables declared outside a function have file scope.

    int globalVar = 10;
    
    void function1() {
          
          
        printf("%d\n", globalVar);  // 可以访问文件作用域的变量
    }
    
    void function2() {
          
          
        printf("%d\n", globalVar);  // 可以访问文件作用域的变量
    }
    
    int main() {
          
          
        printf("%d\n", globalVar);  // 可以访问文件作用域的变量
        function1();
        function2();
        return 0;
    }
    

Lifetime refers to the time range in which a variable exists. The lifetime of a variable depends on its scope and how it is declared. There are the following variable life cycles in C language:

  • Automatic Variables (Automatic Variables) : Variables declared inside functions are automatic variables. Their life cycle begins at the variable definition and ends at the end of the code block in which they are contained. Variables are recreated every time a code block is entered and destroyed when the code block is left.
void function() {
    
    
    int x = 10;  // 自动变量,生命周期与函数调用关联
    printf("%d\n", x);
}

int main() {
    
    
    function();  // 调用函数
    // printf("%d\n", x);  // 错误!变量 x 不在作用域内
    return 0;
}

Static Variables (Static Variables)static : Variables declared using the keyword inside a function are static variables. Their lifetime starts when the program starts executing and ends when the program ends. Static variables exist throughout the execution of the program and are initialized only once.

void function() {
    
    
    static int count = 0;  // 静态变量,生命周期与程序运行关联
    count++;
    printf("%d\n", count);
}

int main() {
    
    
    function();  // 调用函数,输出:1
    function();  // 调用函数,输出:2
    function();  // 调用函数,输出:3
    return 0;
}

Global Variables : Variables declared outside a function are global variables. Their lifetime starts when the program starts executing and ends when the program ends. Global variables exist throughout program execution and are initialized only once.

int globalVar;  // 全局变量

void function() {
    
    
    globalVar = 10;
}

int main() {
    
    
    function();  // 调用函数
    printf("%d\n", globalVar);  // 输出:10
    return 0;
}

4.5 Constants

The definition forms of constants and variables in C language are different.

The constants in C language are divided into the following categories:

  • literal constant
  • constmodified constant variable
  • #defineDefined identifier constants
  • enumeration constant
#include <stdio.h>
//举例
enum Sex {
    
    
    MALE,
    FEMALE,
    SECRET
};
//括号中的MALE,FEMALE,SECRET是枚举常量


int main() {
    
    
    //字面常量演示
    3.14;//字面常量
    1000;//字面常量

    //const 修饰的常变量
    const float pai = 3.14f;//这里的pai是const修饰的常变量
    //pai = 5.14;             //被const修饰后,是不能直接修改的!

    //#define的标识符常量 演示
#define MAX 100
    printf("max = %d\n", MAX);// max = 100

    //枚举常量演示
    printf("%d\n", MALE);  //0
    printf("%d\n", FEMALE);//1
    printf("%d\n", SECRET);//2
    //注:枚举常量的默认是从0开始,依次向下递增1的
    return 0;
}

The above example paiis called a constmodified constant variable. constA modified constant variable in C language only restricts the variable at the grammatical level and paicannot be directly changed, but paiit is still a variable in essence, so it is called a constant variable.

5 string + escape character + comment

5.1 Strings

"hello bit.\n"

This string of characters enclosed by double quotes (Double Quote) is called a string literal (String Literal), or simply a string.

Note: The end of the string is a \0 escape character. \0 is the end mark when calculating the length of the string, and it is not counted as the content of the string.

#include <stdio.h>
//下面代码,打印结果是什么?为什么?(突出'\0'的重要性)
int main()
{
    
    
    char arr1[] = "bit";
    char arr2[] = {
    
    'b', 'i', 't'};
    char arr3[] = {
    
    'b', 'i', 't''\0'};
    printf("%s\n", arr1);  //bit
    printf("%s\n", arr2);  //烫烫
    printf("%s\n", arr3);  //bit
    return 0;
}
  1. arr1is a character array initialized as a string. It contains the characters 'b', 'i', 't' and the null character '\0', and the null character is automatically added at the end of the array. Therefore, printf("%s\n", arr1)what is printed is the complete string "bit".
  2. arr2is a character array initialized with a character list. It contains the characters 'b', 'i', 't', but does not add the null character '\0' at the end. Since %sthe format requires a null-terminated string, printf("%s\n", arr2)continues to access arr2memory following until the first null character is encountered. The memory content behind here is undefined, so the printed result is undefined.
  3. arr3is a character array initialized with a character list, with the null character '\0' explicitly added at the end. Therefore, printf("%s\n", arr3)what is printed is the complete string "bit".

A string in C language is a character array terminated by a null character '\0', which marks the end of the string. If the string is not null-terminated, the string handling functions (such as printf, strcpy, strlenetc.) will not process the string correctly and may cause unexpected results or errors. Therefore, when manipulating strings, it is very important to ensure that the strings are terminated with a null character '\0'.

5.2 Escape characters

If we want to print a directory on the screenc:\code\test.c

How should we write code?

#include <stdio.h>
int main() {
    
    
    printf("c:\code\test.c\n");
    return 0;
}
//输出结果:c:code  est.c

Here I have to mention the escape character. The escape character, as the name suggests, is to change the meaning.

Let's look at some escape characters.

  • \n: newline (newline)
  • \t: tab character (tab)
  • \": double quotes (double quote)
  • \': single quote (single quote)
  • \\: backslash (backslash)
  • \b: backspace
  • \r: carriage return
  • \f: Form feed (form feed)
  • \v: vertical tab (vertical tab)
  • \a: bell symbol (alert)
  • \0: null character
  • \?: question mark (question mark)
  • \ooo: octal character (wherein ooorepresents an octal number, the range is \000to \377)
  • \xhh: hexadecimal character (wherein hhrepresents a hexadecimal number, the range is \x00to \xFF)

It should be noted that if an unknown escape character sequence is used in a string literal, or an out-of-range octal or hexadecimal number is used in a character literal, the compiler may report an error or generate an error. defined behavior. Therefore, when using escape characters, make sure to understand their correct syntax and meaning.

#include <stdio.h>
int main()
{
    
    
    //问题1:在屏幕上打印一个单引号',怎么做?
    //问题2:在屏幕上打印一个字符串,字符串的内容是一个双引号“,怎么做?
    printf("%c\n", '\'');
    printf("%s\n", "\"");
    return 0;
}

Pen questions:

//程序输出什么?
#include <stdio.h>
int main()
{
    
    
    printf("%d\n", strlen("abcdef"));  //6
    // \62被解析成一个转义字符
    printf("%d\n", strlen("c:\test\628\test.c"));  //14
    return 0;
}

5.3 Notes

  1. Unnecessary code in the code can be deleted directly or commented out
  2. Some codes in the code are difficult to understand, you can add a comment text

for example:

#include <stdio.h>
int Add(int x, int y) {
    
    
    return x + y;
}
/*C语言风格注释
int Sub(int x, int y)
{
    return x-y;
}
*/
int main() {
    
    
    //C++注释风格
    //int a = 10;
    //调用Add函数,完成加法
    printf("%d\n", Add(1, 2));
    return 0;
}

Comments come in two flavors:

  • C-style comments/*xxxxxx*/
    • Disadvantage: cannot nest comments
  • C++ style comments//xxxxxxxx
    • You can comment one line or multiple lines

6. Common keywords

auto  break   case  char  const   continue  default  do   double else  enum   
extern float  for   goto  if   int   long  register    return   short  signed
sizeof   static struct  switch  typedef union  unsigned   void  volatile  while

The C language provides a wealth of keywords, which are pre-set by the language itself, and users cannot create keywords by themselves.

6.1 Keyword typedefs

typedef, as the name suggests, is a type definition, and here it should be understood as a type renaming.

for example:

//将unsigned int 重命名为uint_32, 所以uint_32也是一个类型名
typedef unsigned int uint_32;
int main() {
    
    
    //观察num1和num2,这两个变量的类型是一样的
    unsigned int num1 = 0;
    uint_32 num2 = 0;
    return 0;
}

6.2 Keyword static

In C language: static is used to modify variables and functions

  1. Decorate local variables - called static local variables
  2. Decorate global variables - called static global variables
  3. Decorator functions - called static functions

Modify local variables

Example 1:

#include <stdio.h>
void test() {
    
    
    int i = 0;
    i++;
    printf("%d ", i);
}

int main() {
    
    
    int i = 0;
    for (i = 0; i < 10; i++) {
    
    
        test();
    }
    return 0;
}

Output result:

1 1 1 1 1 1 1 1 1 1

Add static:

#include <stdio.h>
void test() {
    
    
    //static修饰局部变量
    static int i = 0;
    i++;
    printf("%d ", i);
}

int main() {
    
    
    int i = 0;
    for (i = 0; i < 10; i++) {
    
    
        test();
    }
    return 0;
}

Output result:

1 2 3 4 5 6 7 8 9 10

Compare the effect of code 1 and code 2 to understand the significance of static modification of local variables.

in conclusion:

Static modification of local variables changes the life cycle of variables

Let static local variables still exist outside the scope, and the life cycle will not end until the end of the program.

Decorate global variables

Example:

//代码1
//add.c
int g_val = 2018;
//test.c
int main() {
    
    
    printf("%d\n", g_val);
    return 0;
}

//代码2
//add.c
static int g_val = 2018;
//test.c
int main() {
    
    
    printf("%d\n", g_val);
    return 0;
}

Code 1 is normal, and code 2 will have a connectivity error when compiling.

in conclusion:

A global variable is modified by static, so that this global variable can only be used in this source file, and cannot be used in other source files.

modifier function

Example:

//代码1
//add.c
int Add(int x, int y) {
    
    
    return x + y;
}
//test.c
int main() {
    
    
    printf("%d\n", Add(2, 3));
    return 0;
}
//代码2
//add.c
static int Add(int x, int y) {
    
    
    return x + y;
}
//test.c
int main() {
    
    
    printf("%d\n", Add(2, 3));
    return 0;
}

Code 1 is normal, and code 2 will have a connectivity error when compiling.

in conclusion:

A function is modified by static, so that this function can only be used in this source file, and cannot be used in other source files.

7. #define defines constants and macros

//define定义标识符常量
#define MAX 1000
//define定义宏
#define ADD(x, y) ((x) + (y))
#include <stdio.h>
int main() {
    
    
    int sum = ADD(2, 3);
    printf("sum = %d\n", sum);//sum = 5

    sum = 10 * ADD(2, 3);
    printf("sum = %d\n", sum);//sum = 50

    return 0;
}

Guess you like

Origin blog.csdn.net/ikun66666/article/details/131296316