一个较大的程序,一般分为若干个程序块,没个程序块实现特定的功能
5步骤 1返回值类型 2函数名 3参数表列 4函数体语句 5return表达式
int add (int num1,int num2)//num1,num2为形参
{
int sum = num1 + num2;
return sum;
}
定义两个数交换的函数
void swap(int num1, int num2)
{
cout << "交换前" << endl;
cout << num1 << endl;
cout << num2 << endl;
int temp = num1;
num1 = num2;
num2 = temp;
cout << "交换后" << endl;
cout << num1 << endl;
cout << num2 << endl;
}
值传递
int a = 10;
int b = 20;
cout << "a=" << a << endl;
cout << "b=" << b << endl;
swap(a, b); //上面有函数的定义
cout << "结尾实参" << endl;
cout << "a=" << a << endl;
cout << "b=" << b << endl;//证明实参并没有被形参所改变
//当值传递时,形参发生任何的改变都不会影响实参
函数的常见形式
有参无返,有参有返,无参无返,无参无返
//无参无返
void test1()
{
cout << "test1" << endl;
}
//有参无返
void test2(int a)
{
cout << "test2" << endl;
}
//无参有返
int test3()
{
cout << "test3" << endl;
return 1000;
}
//有参有返
int test4(int a)
{
cout << "test4=" << a <<endl;
return a;
}
int main()
{
//无参无返调用
test1();
//有参无返调用
test2(100);
//无参有返调用
int num = test3();
cout << "num-" << num << endl;
//有参有返调用
int num2 = test4(1000);
cout << "test4=" << num2 << endl;
system("pause");
return 0;
}
函数的声明
int max(int a, int b);//声明可以有多次但定义只能有一次
int max(int a, int b);
int max(int a, int b);
//比较函数:实现两个数返回较大值
int max(int a,int b)
{
return a > b?a:b;
}
函数定义
void swap(int a, int b);
void swap(int a, int b)
{
int temp = a;
a = b;
b = temp;
cout << "a=" << a << endl;
cout << "b=" << b << endl;
}
函数的调用
int a = 10;
int b = 20;//a,b为实参
int d = 34;
//调用法则
int c=add(a, d); //当调用时,实参会传给形参然后进行计算最后返回
cout << c << endl;
函数的分文件编写
1.创建后缀名为.h的头文件
2.创建后缀名为.cpp的源文件
3.在头文件里写函数的声明
4.在源文件中写函数的定义
int a = 10;
int b = 20;
swap(a, b);