C语言中的函数概念

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

1.函数是什么?
在计算机科学中,子程序(函数)是一个大型程序中的某部分代码,由一个或多个语句构成,它负责完成某项特定任务,而且相较于其他代码,具备相对的独立性。

一般会有输入参数并由返回值,提供对过程的封装细节的隐藏,这些代码通常被集成软件库

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

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

例题1:计算两个数的和

 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;

}

库函数

c语言本身提供的函数
C语言中的库函数有,还有头文件。
*参考网站:www.cplusplus.com
https://zh.cppreference.com/

我们来看一下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;
}

C语言中的函数概念

memset函数

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

C语言中的函数概念

自定义函数

自行定义的函数

#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);
}

C语言中的函数概念

例题二
写一个函数,来交换两个整型变量中的内容
#include <stdio.h>
//指针变量接收地址

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;
}

C语言中的函数概念

猜你喜欢

转载自blog.51cto.com/15100290/2675340