C language phase III (detailed explanation of 10000 word function array operator)

preface This issue is the third issue of C language. If you need to see the framework of the previous issues, you can cl...
Definition of function
Classification of functions
Function parameters
function call
Nested calls and chained access to functions
Declaration and definition of functions
Function recursion (tower of Hanoi)
Creation and initialization of one-dimensional array
Use of one-dimensional arrays
Storage of one-dimensional array in memory
Creation and initialization of two-dimensional array
Use of two-dimensional arrays
Storage of two-dimensional array in memory
Array out of bounds
Array as function parameter (address call)
Introduction to all operators
Expression evaluation

preface
  • This issue is the third issue of C language. If you need to see the framework of the previous issues, you can click on my blog to have a look.
  • The next blogger will summarize the pointer. At the same time, I will share some dry goods from time to time. Look forward to your return visit!
    ❤️ : Love programming learning and look forward to communicating together!
    🙏: The level of bloggers is limited. If you find any errors, please let us know. Thank you!
function

Definition of function

We often see the concept of function in mathematics. But do you know the functions in C language?

  • Wikipedia definition of function: subroutine
  • In computer science, subroutine (English: subroutine, procedure, function, routine, method, subroutine, callable unit) is a part of code in a large program,
    Consists of one or more statement blocks. It is responsible for completing a specific task and has relative independence compared with other codes.
  • Generally, there are input parameters and return values, which provide encapsulation of the process and hiding of details. These codes are usually integrated into software libraries.

Classification of functions

  • Library function
  • Custom function

Why do library functions have library functions?

  • We know that when we learn C language programming, we always can't wait to know the result after a code is written, and want to print the result to our screen. At this time, we will frequently use a function: print the information to the screen according to a certain format, and use the printf function.
  • Or when entering a number, use the scanf function.
  • For the basic functions described above, every programmer may use them in the development process. In order to support portability and improve program efficiency, a series of similar library functions are provided in the basic library of C language for the convenience of programmers
    Conduct software development.
  • To sum up, the library functions commonly used in C language are:
    • IO function
    • String operation function
    • Character manipulation function
    • Memory operation function
    • Time / date function
    • Mathematical function
    • Other library functions
  • When we use a library function, we don't know how to use the header file?
    • The Chinese version of a document is highly recommended here http://zh.cppreference.com
    • When you use it, you only need to find it. You don't need to remember all the library functions. You just need to learn how to find it.

Custom function

  • If library functions can do everything, what do programmers do?
  • Therefore, it is more important to customize functions.
  • Like library functions, custom functions have function names, return value types, and function parameters.
  • But the difference is that these are designed by ourselves. This gives programmers a lot of room to play.
  • Composition format of function:
Return type function name(Parameter type formal parameter 1, parameter type formal parameter 2) { Function body; Return value; }
ret_type fun_name(para1, * ) { statement;//Statement item } //ret_type return type //fun_name function name //Param1 function parameters
  • Let's take an example
  • Write a function to find the maximum value of two integers.
#include <stdio.h> //get_ Design of Max function int get_max(int x, int y)//This is get_ The definition of Max function, where x and y are formal parameters, which are used to receive the value from the argument. { return (x>y)?(x):(y);//Return value } int main() { int num1 = 10; int num2 = 20; int max = get_max(num1, num2);//Here is the call to get_max function, num1 and num2 are arguments. printf("max = %d\n", max); return 0; }

Function parameters

Actual parameter (actual parameter)

  • The parameters really passed to the function are called arguments.
  • No matter what type of arguments are, they must have definite values when making a function call in order to pass these values to the shape
    ginseng
  • Arguments can be constants, variables, expressions, functions, etc.

Formal parameter (formal parameter)

  • Like the above, the arguments (num1, num2) and formal parameters (x, y) do not use the same space. That is, their values are at different addresses.
  • Formal parameters refer to the variables in parentheses after the function name, because formal parameters are instantiated only when the function is called (within the assignment)
    Storage unit), so it is called formal parameter.
  • Formal parameters are automatically destroyed when the function call is completed. Therefore, formal parameters only exist in functions
    Effective.
  • We can simply think that after the formal parameter is instantiated, it is actually equivalent to a temporary copy of the argument.

function call

Value passing call

  • The formal parameters and arguments of the function occupy different memory blocks respectively, and the modification of the formal parameters will not affect the arguments.
  • Write a function to judge whether a number is a prime number.
#include<stdio.h> #include<math.h> int is_prime(int n) { int i = 0; for (i = 2; i < sqrt(n); i ++) { if (n % i == 0) { return 0; } } return 1; } int main() { int n = 0; scanf("%d", &n); int ret = is_prime(n); if (ret == 1) { printf("It's a prime"); } else if(ret == 0) { printf("Not prime"); } return 0; }

Address call

  • Addressing call is a way to call a function by passing the memory address of the variable created outside the function to the function parameters.
  • This parameter transfer method can establish a real relationship between the function and the variables outside the function, that is, the function can be operated directly
    As an external variable of a function.
  • Special attention should be paid to the array name in addressing calls.

Nested calls and chained access to functions

Nested Call

  • Functions and functions can be combined according to actual needs, that is, they call each other.
#include <stdio.h> void new_line() { printf("hehe\n"); } void three_line() { int i = 0; for(i=0; i<3; i++) { new_line();Second call } } int main() { three_line();//First call return 0; }
  • Functions can be called nested, but cannot be defined nested.

Chain access (understand)

  • Take the return value of one function as an argument to another function.
#include <stdio.h> #include <string.h> int main() { char arr[20] = "hello"; int ret = strlen(strcat(arr,"bit"));//Here is an introduction to the strlen function printf("%d\n", ret); return 0; } #include <stdio.h> int main() { printf("%d", printf("%d", printf("%d", 43))); //What's the result? //Note: the return value of the printf function is the number of characters printed on the screen return 0; }

Declaration and definition of functions

Declaration of function

  • Tell the compiler what a function is called, what the parameters are and what the return type is. But is there a function
    The statement can't decide.
  • The declaration of a function usually appears before the use of the function. To meet the requirements of declaration before use.
  • The declaration of the function is usually placed in the header file. (. h ending file)
    ###Definition of function
  • The definition of function refers to the specific implementation of the function and explains the function implementation of the function.
  • It is usually placed in the source file (. The file ending in c)

Function recursion (tower of Hanoi)

What is recursion?

  • The programming technique of a program calling itself is called recursion.
  • As an algorithm, recursion is widely used in programming languages. A process or function has a method to call itself directly or indirectly in its definition or description. It usually transforms a large and complex problem layer by layer into a smaller problem similar to the original problem. The recursive strategy can describe the multiple repeated calculations required in the problem-solving process with only a small number of programs, which greatly reduces the amount of code of the program.
  • The main way of thinking about recursion is to make big things small

Two necessary conditions for recursion

  • There is a constraint. When this constraint is met, recursion will not continue.
  • Getting closer to this constraint after each recursive call
  • The following is a typical recursive problem, the tower of Hanoi problem. The picture comes from Baidu.
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> int Hanio_twice(int num) { if(1 == num) return 1; else return 2 * Hanio_twice(num - 1) + 1; } int main() { int num = 0; scanf("%d", &num);//Tower number int ret = Hanio_twice(num); printf("complete%d The Hanoi Tower on the first floor needs%d step\n", num, ret); return 0; }
array

Creation and initialization of one-dimensional array

  • An array is a collection of elements of the same type.

Array creation

  • How to create an array:
type_t arr_name [const_n]; //type_t is the element type of the index group //const_n is a constant expression that specifies the size of the array.
  • Instance of array creation:
//Code 1 int arr1[10]; //Code 2 int count = 10; int arr2[count];//When can arrays be created normally? //Code 3 char arr3[10]; float arr4[1]; double arr5[20];

Initialization of array

  • Array initialization means that some reasonable initial values (initialization) are given to the contents of the array while creating the array.
  • The code is as follows
int arr1[10] = ; int arr2[] = ; int arr3[5] = ; char arr4[3] = {'a',98, 'c'}; char arr5[] = {'a','b','c'}; char arr6[] = "abcdef";
  • When creating an array, if you want to not specify the determined size of the array, you have to initialize it. The number of elements of the array is determined according to the initialization content.
  • But for the following code, we should distinguish how to allocate memory
char arr1[] = "abc";//Four elements are stored in memory, namely 'a' ', B' ', C' '\ 0' char arr2[3] = {'a','b','c'};//And here's' a''b''c '
  • The end flag of the string is' \ 0 '

Use of one-dimensional arrays

  • For the use of arrays, we introduced an operator: [], subscript reference operator. It's actually an array access operator.
    Let's look at the code:
#include <stdio.h> int main() { int arr[10] = ;//Incomplete initialization of array int sz = sizeof(arr)/sizeof(arr[0]);//Count the number of elements in the array //Assign a value to the contents of the array. The array is accessed by subscript, which starts from 0. So: int i = 0;//Subscript for(i=0; i<10; i++) { arr[i] = i;//Here i write 10, okay? Of course not. Writing 10 means that the 11th element is accessed, and the array will cross the boundary. } for(i=0; i<10; ++i) { printf("%d ", arr[i]); //Output the contents of the array } return 0; }
  • Summary:
    • Arrays are accessed using subscripts that start at 0.
    • The size of the array can be calculated.
int arr[10]; int sz = sizeof(arr)/sizeof(arr[0]);//40/4=10; So the length of the array is 10

Storage of one-dimensional array in memory

#include <stdio.h> int main() { int arr[10] = ; int i = 0; int sz = sizeof(arr)/sizeof(arr[0]); for(i=0; i<sz; ++i) { printf("&arr[%d] = %p\n", i, &arr[i]);//We print out the addresses of 10 elements. } return 0; }
  • The printing results are as follows

  • It can be seen from the picture.

  • Each address differs by four digits, 9C and A0 differ by four digits, followed by four digits (these digits are hexadecimal).

    • Arrays are stored continuously in memory.
    • Use the array name to point to the address with the smallest storage space

Creation and initialization of two-dimensional array

//Array creation int arr[3][4]; char arr[3][5]; double arr[2][4];
//Array initialization int arr[3][4] = ; int arr[3][4] = {,}; int arr[][4] = {,};//If a two-dimensional array is initialized, rows can be omitted and columns cannot be omitted

Use of two-dimensional arrays

  • The use of two-dimensional arrays is also through subscripts.
  • The code is as follows. Create a 3 * 4 two-dimensional array and initialize the input and output of the array. The figure is as follows.
#include <stdio.h> int main() { int arr[3][4] = ;//Create a two-dimensional array of three rows and four columns int i = 0; for(i=0; i<3; i++) { int j = 0; for(j=0; j<4; j++) { arr[i][j] = i*j;//Cyclic assignment } } for(i=0; i<3; i++) { int j = 0; for(j=0; j<4; j++) { printf("%d ", arr[i][j]);//Cyclic output } } return 0; }

Storage of two-dimensional array in memory

  • Like a one-dimensional array, here we try to print each element of a two-dimensional array.
#include <stdio.h> int main() { int arr[3][4]; int i = 0; for(i=0; i<3; i++) { int j = 0; for(j=0; j<4; j++) { printf("&arr[%d][%d] = %p\n", i, j,&arr[i][j]); }//Print out the address of each element of the 3 * 4 two-dimensional array to study its storage in memory. } return 0; }
  • The printing results are as follows.
  • Like the one-dimensional array above, skipping four digits each time shows that the two-dimensional array is also continuous in memory.

Array out of bounds

  • The subscript of an array is scoped.
  • The lower specification of the array starts from 0. If the array has n elements, the subscript of the last element is n-1.
  • Therefore, if the subscript of the array is less than 0 or greater than n-1, the array is accessed beyond the bounds and beyond the access of the legal space of the array.
  • However, the compiler itself does not report errors, so programmers need to pay more attention at this time.
#include <stdio.h> int main() { int arr[10] = ;//Ten elements are defined. int i = 0; for(i=0; i<=10; i++) { printf("%d\n", arr[i]);//When i equals 10, the 11th element is accessed! } return 0; }

Array as function parameter (address call)

  • Let's take the wrong bubble sorting algorithm as an example.
#include <stdio.h> void bubble_sort(int arr[]) { int sz = sizeof(arr)/sizeof(arr[0]);//This line of code is wrong. The wrong thinking is that it should be 40 / 4 = 10 int i = 0;//But the result is 4 / 4. The reason is that sizeof (arr) calculates the address of the first element. The address size of the first element depends on the machine. In terms of 32 bits, it is 4 bytes. for(i=0; i<sz-1; i++) { int j = 0; for(j=0; j<sz-i-1; j++) { if(arr[j] > arr[j+1]) { int tmp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = tmp; } } } } int main() { int arr[] = ; bubble_sort(arr);//The name passed is the array name, and the default is the address of the first element of the array. for(i=0; i<sizeof(arr)/sizeof(arr[0]); i++) { printf("%d ", arr[i]); } return 0; }
  • So we come to a conclusion: when an array is used as a function parameter, we don't pass the of the whole array. The address of the first element of the array is passed. Address calling

What is an array name

#include <stdio.h> int main() { int arr[10] = ; printf("%p\n", arr);// printf("%p\n", &arr[0]); printf("%d\n", *arr); return 0; }

  • Three output results can prove that the array name arr is the address of the first element!

Two exceptions

  • In two cases, the array name does not represent the address of the first element
    1. Sizeof (arr) when placing an array name separately, sizeof calculates the byte size of the entire array.
    2. Take the address plus the array name to represent the address of the whole array.
Operator

Introduction to all operators

arithmetic operator

+ - * / %
  • In addition to the% operator, several other operators can act on integers and floating-point numbers.
  • For the / operator, if both operands are integers, perform integer division. As long as there are floating-point numbers, it is floating-point division.
  • %The two operands of the operator must be integers. Returns the remainder after division.

Shift operators

For the shift operator and the bit operator, the operation is a binary sequence.

  • Shift left operator

Shift rule: discard on the left and fill 0 on the right

  • Shift right operator

Shift rule:
1. The logical shift is filled with 0 on the left and discarded on the right
2. The left side of arithmetic shift is filled with the sign bit of the original value, and the right side is discarded

Bitwise operators

& //Bitwise AND | //Bitwise OR ^ //Bitwise XOR Note: their operands must be binary sequence integers.
  • An abnormal interview question
  • You cannot create temporary variables to exchange the values of a and b.
#include <stdio.h> int main() { int a = 10; int b = 20;//Use the following two conclusions. a = a^b;//1. The result of two identical XORs is 0 b = a^b;//2. The result of any number and 0 XOR is itself. a = a^b; printf("a = %d b = %d\n", a, b); return 0; }

Assignment operator

int a = 10; int x = 0; int y = 20;
  • Compound assignment operator
+=//a+=1 is equivalent to a = a+1 -= *= /= %= >>= <<= &= |= ^=
  • The compound assignment operator looks simpler.

unary operator

! Logical reverse operation - negative + positive & Get address sizeof The type length of the operand in bytes ~ Bitwise negation of a number -- Front and rear-- ++ Front and rear++ * Indirect access operator(dereference operator ) (type) Cast type

Relational operator

> >= < <= != Used to judge "inequality" == Used to judge "equal"
  • Pay special attention to the double equal sign when judging if statements. Distinguish between = = and =.

comma expression

  • Comma expressions are multiple expressions separated by commas.
  • Comma expression, executed from left to right. The result of the entire expression is the result of the last expression.

Subscript reference, struct member access, function call

[ ] Subscript reference operator ( ) function call operator . structural morphology.Member name (point operator) -> Structure pointer->member name

Expression evaluation

  • The order in which expressions are evaluated is partly determined by the priority and associativity of operators.
  • Similarly, the operands of some expressions may need to be converted to other types during evaluation.

Implicit type conversion

  • The integer arithmetic operation of C is always performed at least with the precision of the default integer type.
  • To achieve this precision, the characters and short operands in the expression are converted to normal integers before use. This conversion is called integer promotion.
//Example 1 char a,b,c; ... a = b + c;//The values of b and c are promoted to normal integers, and then the addition operation is performed.

Arithmetic conversion

  • If the operands of an operator are of different types, the operation cannot be performed unless one of the operands is converted to the type of the other operand. The following hierarchy is called ordinary arithmetic conversion.
float f = 3.14; int num = f;Implicit conversion, there will be precision loss.

Properties of the operator

There are three factors that affect the evaluation of complex expressions. (judge in the following order)

  1. Determine the priority of the operator first
  2. Then judge the associativity of operators
  3. Whether to control the evaluation order.

  • Conclusion: if the expression we write cannot determine the unique calculation path through the properties of the operator, there is a problem with this expression.
  • Note. This drawing refers to Baidu
summary
  • The above are the details of functions, arrays and operators. It is recommended to collect and review them repeatedly.
  • Finally, if you think my article is helpful to you 🎉 Welcome to pay attention 🔎 give the thumbs-up 👍 Collection ⭐ Leave a message 📝.

17 November 2021, 04:55 | Views: 4768

Add new comment

For adding a comment, please log in
or create account

0 comments