函数语法

image-20220113000425936


函数的调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include<iostream>
using namespace std;
//num1和num2没有实际值,是形参
int add(int num1, int num2)
{
int sum = 0;
sum = num1 + num2;
return sum;
}
int main()
{
//main函数中调用add函数
int a = 10;
int b = 20;
//函数调用语法 函数名(参数)
/*a,b为实际参数,简称实参
当调用函数的时候,实参的值会传递给形参*/
int c = add(a, b);
cout << "c=" << c<<endl;
//改变a,b的值
a = 100;
b = 350;
c = add(a, b);
cout << "c=" << c << endl;
system("pause");
return 0;
}

函数的几种表达方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include<iostream>
using namespace std;
//函数常见样式
//1.无参无返
void test01()
{
cout << "this is test01" << endl;
}
//有参无返
void test02(int a)
{
cout << "this is test02 =" <<a<< endl;
}
//无参有返
int test03()
{
cout << "this is test03" << endl;
return 1000;
}
//有参有返
int test04(int num2, int num3)
{
int sum = num2 + num3;
cout << "this is test04" << endl;
return sum;
}
int main()
{
//无参无返函数调用
test01();
//有参无返函数调用
test02(100);
//无参有返函数调用
int num1 = test03();
cout << num1 << endl;
//有参有返函数调用
int a = 50, b = 150;
int c = test04(a, b);
cout << c << endl;
system("pause");
return 0;
}

函数的声明

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<iostream>
using namespace std;
//函数的声明
//比较函数,实现两个整型数字进行比较,返回较大的值

//定义
//提前告诉函数的存在,可以利用函数的声明
//声明可以有多次,但定义只能有一次
int max(int a, int b);

int main()
{
int a = 10;
int b = 15;
cout << max(a,b) << endl;
system("pause");
return 0;
}
//定义
int max(int a, int b)
{
return a > b ? a : b;
}

函数的分文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include<iostream>
using namespace std;
#include"swap.h"
//函数的分文件
//实现两个数字交换
//函数的声明
//void swap(int a, int b);
//定义
//void swap(int a, int b)
//{
// int temp;
// temp = a;
// a = b;
// b = temp;
// cout << "a=" << a << endl;
// cout << "b=" << b << endl;
//}
//分文件
//创建.h的后缀的头文件
//创建.cpp的后缀的源文件
//在头文件中写函数的声明
//在源文件中写函数的定义
int main()
{
int a = 500;
int b = 600;
swap(a, b);
system("pause");
return 0;
}