为什么要用函数
在程序设计中,我们会发现一些程序段,在程序的不同地方反复出现,我们就可以写成函数,反复使用。体现“模块化编程”的思想。
函数的定义
数据类型 函数名(形式参数){
函数体
}
void f(){
cout << "hello" << '\n';
}
void f(int x){
cout << x << '\n';
}
int f(int a, int b){
return a + b;
}
函数的声明、定义和调用
函数声明告诉编译器函数的名称、返回类型和参数。
函数定义提供了函数的实际主体。
函数调用
#include <iostream>
using namespace std;
void f()
{
cout << "函数调用一次" << "\n";
}
int main()
{
f();
f();
return 0;
}