Function concept in C language

函数的基本使用和递归
1.函数是什么
2.库函数
3.自定义函数
4.函数参数
5.函数调用
6.函数的嵌套调用和链式访问
7.函数的声明和定义
8.函数递归

1. What is a function?
In computer science, a subroutine (function) is a certain part of the code in a large program, which is composed of one or more statements. It is responsible for completing a specific task and is relatively independent of other codes.

Generally, there are input parameters and return values, which provide the encapsulation of the process and the hiding of details . These codes are usually integrated software libraries

函数的基本组成: ** 返回类型  函数名 和函数参数**
{
函数体;
}

列如:  int  MEI(int x,int y);
{
int z=x+y;
return z;
}

Example 1: Calculate the sum of two numbers

 int ADD(int x, int y) {
    int z = x + y;
    return z;
}
#include <stdio.h>
int main() {
    int a = 10;
    int b = 20;
    int sum = ADD(a, b);
    printf("sum=%d", sum);
    return 0;

}

Library Functions

Functions provided by the
C language There are library functions in the C language, as well as header files.
* Reference website: www.cplusplus.com
https://zh.cppreference.com/

Let's take a look at the function strcpy

#include <stdio.h>
//strcpy的头文件
#include <string.h>

int main() {
    char arr1[] = "bit";
    char arr2[20] = "1111";
    //把arr1数组中的内容copy到arr2中,会覆盖!!
    strcpy(arr2, arr1);
    //打印arr2
    printf("%s", arr2);
    return 0;
}

Function concept in C language

memset function

#include <stdio.h>
#include <string.h>
int main() {
    //memset
    char arr[] = "hello world";
    //把arr中前五个字符替换成*号
    memset(arr, '*', 5);
    printf("%s", arr);
    return 0;
}

Function concept in C language

Custom function

Self-defined function

#include<stdio.h>
//定义函数
int get_max(int x, int y) {
    if (x > y)
        return x;
    else
        return y;

}
int main() {
    int a = 10;
    int b = 20;
    int max = get_max(a, b);
    printf("max=%d\n", max);
}

Function concept in C language

Example 2:
Write a function to exchange the contents of two integer variables
#include <stdio.h>
//Pointer variable receiving address

void SWAP (int* x, int* y) {
    int tmp = 0;
    tmp = *x;
    *x = *y;
    *y = tmp;
}
int main() {
    int a = 10;
    int b = 20;
    printf("a=%d,b=%d \n", a, b);
    //把a和b的地址传过去
    SWAP(&a, &b);
    printf("a=%d,b=%d", a, b);
    return 0;
}

Function concept in C language

Guess you like

Origin blog.51cto.com/15100290/2675340