47.函数基本概念和用法

目录

一.什么是函数

二.定义函数

三.函数调用

四.函数的声明

五.函数的分类

六.视频教程


一.什么是函数

每个C语言程序至少有一个函数,即主函数man函数。除了主函数以外,我们也可以自定义其他函数。

函数可以看作是某个功能的封装,而且使用函数可以省去重复代码的编写,降低代码重复率。

二.定义函数

返回值(类型) 函数名称(函数参数)
{
    程序块
}

例子1:定义一个max函数,无返回值,无函数参数

void max(void)
{
       int result = 0;
       printf("max is %d!\n",result);
  
}

例子2:定义一个max函数,返回值是0,int类型,无函数参数

int  max(void)
{
       int result = 0;
       printf("max is %d!\n",result);
       return 0;
  
}

例子3:定义一个max函数,返回值是最大值,int类型,函数参数为int类型的a和b

int max(int a,int b)
{
       int result = 0;
       if(a > b){
              result = a;
       }else{
              result = a; 
       }

       return result;
  
}

三.函数调用

在main函数中调用上文中的max函数

#include <stdio.h>


int max(int a,int b)
{
       int result = 0;
       if(a > b){
              result = a;
       }else{
              result = b; 
       }
       return result;
  
}



void main(void)
{

       int ret;
       ret = max(1,2);
       printf("max is %d!\n",ret);

}

执行结果:

四.函数的声明

函数声明可以告诉编译器函数名称和如何调用函数。而且如果在一个源文件中调用另外一个源文件中定义的函数,函数声明是必须的。

举例:

对上文中例子3函数声明:

#include <stdio.h>


int max(int a,int b);

int max(int a,int b)
{
       int result = 0;
       if(a > b){
              result = a;
       }else{
              result = b; 
       }
       return result;
  
}



void main(void)
{

       int ret;
       ret = max(1,2);
       printf("max is %d!\n",ret);

}

其中int max(int a,int b);也可以写成int max(int,int);

五.函数的分类

1.库函数

库函数:由系统提供的,用户不必自己定义这些函数,可以直接使用它们,如我们常用的打印函数printf()。

C语言中库函数查询网址:cplusplus.com/reference/cstdio/

2.自定义函数

自定义函数:用以解决用户需求而专门定义的函数。

六.视频教程

48.函数基本概念和用法_哔哩哔哩_bilibili

相关推荐

  1. git的基本概念

    2024-04-04 11:44:03       26 阅读
  2. Git概念

    2024-04-04 11:44:03       8 阅读
  3. CSS的基本结构

    2024-04-04 11:44:03       48 阅读
  4. PHP类对象概念

    2024-04-04 11:44:03       9 阅读
  5. SummaryWriter函数

    2024-04-04 11:44:03       30 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-04 11:44:03       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-04 11:44:03       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-04 11:44:03       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-04 11:44:03       18 阅读

热门阅读

  1. 课时84:流程控制_select条件控制_案例实践

    2024-04-04 11:44:03       13 阅读
  2. 2404d,d语言1月会议

    2024-04-04 11:44:03       14 阅读
  3. 【云原生篇】K8S之StatefulSet 详解

    2024-04-04 11:44:03       18 阅读
  4. Python如何下载视频

    2024-04-04 11:44:03       17 阅读
  5. 全志A40i android7.1 移植wifi驱动的一般流程

    2024-04-04 11:44:03       12 阅读
  6. 【Python】Pillow支持的图像文件格式

    2024-04-04 11:44:03       11 阅读
  7. microPython的源码解析之 lexer.c

    2024-04-04 11:44:03       11 阅读
  8. cmake 怎么给CMAKE_TOOLCHAIN_FILE赋值

    2024-04-04 11:44:03       13 阅读