Functions and Header Files
function
Overview
Purpose: Encapsulate a segment of frequently used code to reduce repetitive code.
A large program is generally divided into several modules, each of which implements specific functions.
function definition
A function definition typically involves 5 main steps:
- Return value type
- Function Name
- Parameter Table
- Function body statements
- return expression
Syntax:
返回值类型 函数名 (参数列表)
{
函数体语句
return表达式
}
Running/Observing Results: This is a syntax or interface example, focus on the writing style; run and verify after incorporating it into a complete program.
- Return type: A function can return a value. In the function definition
- Function name: give the function a name
- Parameter list: the data passed in when using this function
- Function body statements: The code inside curly braces, which are the statements that need to be executed within the function.
- Return expressions are tied to the return type, and after a function completes execution, it returns the corresponding data.
Example: Define an addition function to add two numbers.
//函数定义
int add(int num1, int num2)
{
int sum = num1 + num2;
return sum;
}
Running/Observing Results: This is a syntax or interface example, focus on the writing style; run and verify after incorporating it into a complete program.
Function call
Function: Use predefined functions
Syntax: 函数名(参数)
Example:
//函数定义
int add(int num1, int num2) //定义中的num1,num2称为形式参数,简称形参
{
int sum = num1 + num2;
return sum;
}
int main() {
int a = 10;
int b = 10;
//调用add函数
int sum = add(a, b);//调用时的a,b称为实际参数,简称实参
cout << "sum = " << sum << endl;
a = 100;
b = 100;
sum = add(a, b);
cout << "sum = " << sum << endl;
return 0;
}
Running/Observation Results: After running, the corresponding content will be printed according to the output statements. The variable values can be inferred based on the order of initialization, assignment, and function calls.
Summary: In a function definition, parameters within parentheses are called formal parameters, while parameters passed during function invocation are called actual parameters.
Pass-by-value
- Pass-by-value means that when a function is called, the actual parameters pass their values to the formal parameters.
- When passing by value, ==if the parameter changes, it does not affect the argument==.
Example:
void swap(int num1, int num2)
{
cout << "交换前:" << endl;
cout << "num1 = " << num1 << endl;
cout << "num2 = " << num2 << endl;
int temp = num1;
num1 = num2;
num2 = temp;
cout << "交换后:" << endl;
cout << "num1 = " << num1 << endl;
cout << "num2 = " << num2 << endl;
//return ; 当函数声明时候,不需要返回值,可以不写return
}
int main() {
int a = 10;
int b = 20;
swap(a, b);
cout << "mian中的 a = " << a << endl;
cout << "mian中的 b = " << b << endl;
return 0;
}
Running/Observation Results: After running, the corresponding content will be printed according to the output statements. The variable values can be inferred based on the order of initialization, assignment, and function calls.
Summary: When passing by value, the formal parameter cannot modify the actual argument.
Common Styles of Functions
There are 4 common function styles.
- no parameter no return
- function with parameters but no return value
- No parameters, but returns a value.
- with parameters and return values
Example:
//函数常见样式
//1、 无参无返
void test01()
{
//void a = 10; //无类型不可以创建变量,原因无法分配内存
cout << "this is test01" << endl;
//test01(); 函数调用
}
//2、 有参无返
void test02(int a)
{
cout << "this is test02" << endl;
cout << "a = " << a << endl;
}
//3、无参有返
int test03()
{
cout << "this is test03 " << endl;
return 10;
}
//4、有参有返
int test04(int a, int b)
{
cout << "this is test04 " << endl;
int sum = a + b;
return sum;
}
Running/Observing the results: After running, the example will print variable values or addresses; address values depend on the runtime environment, so focus on observing the relative positioning and pointer changes of similar objects.
Function Declaration
Purpose: Specifies to the compiler the function name and how the function is to be called. The actual implementation of the function can be defined separately.
- Function declarations can be made multiple times, but a function can only have one definition.
Example:
//声明可以多次,定义只能一次
//声明
int max(int a, int b);
int max(int a, int b);
//定义
int max(int a, int b)
{
return a > b ? a : b;
}
int main() {
int a = 100;
int b = 200;
cout << max(a, b) << endl;
return 0;
}
Running/Observation Results: After running, the corresponding content will be printed according to the output statements. The variable values can be inferred based on the order of initialization, assignment, and function calls.
Separating functions into different files
Purpose: To make the code structure clearer.
Writing functions in separate files typically involves 4 steps.
- Create a header file with a .h extension.
- Create a source file with the .cpp extension.
- 在头文件中,函数的声明(或称为原型)用于告知编译器函数的名称、返回类型以及参数类型。这使得在源文件中调用该函数之前,编译器就能知道该函数的接口。
基本语法:
返回类型 函数名(参数类型1 参数名1, 参数类型2 参数名2, ...);
示例: 假设有一个函数用于计算两个整数的和。
在头文件 math_utils.h 中声明:
#ifndef MATH_UTILS_H // 包含保护(Include Guard)
#define MATH_UTILS_H
// 函数声明(原型)
int add(int a, int b);
#endif // MATH_UTILS_H
在源文件 math_utils.c 中实现:
#include "math_utils.h"
// 函数定义(实现)
int add(int a, int b) {
return a + b;
}
在另一个源文件 main.c 中使用:
#include <stdio.h>
#include "math_utils.h" // 包含头文件,以获取函数声明
int main() {
int result = add(3, 5); // 编译器通过头文件中的声明,知道此调用合法
printf("Sum: %d\n", result);
return 0;
}
关键点:
- 声明 vs 定义:头文件中只放声明(告诉编译器“有这样一个函数”),而定义(函数的具体实现)放在对应的源文件(.c 或 .cpp 文件)中。
- 包含保护(Include Guard):使用
#ifndef、#define、#endif可以防止头文件被多次包含而导致重复声明的错误。 - 作用:通过包含头文件,其他源文件可以安全地调用该函数,而无需知道其具体实现细节,实现了接口与实现的分离。
- Write function definitions in the source files.
Example:
//swap.h文件
#include<iostream>
using namespace std;
//实现两个数字交换的函数声明
void swap(int a, int b);
Run/Observation Results: This section is syntax definition-focused, typically requiring compilation together with the calling code. Pay attention to the definition method and usage location.
//swap.cpp文件
#include "swap.h"
void swap(int a, int b)
{
int temp = a;
a = b;
b = temp;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
}
Running/Observation Results: After running, the corresponding content will be printed according to the output statements. The variable values can be inferred based on the order of initialization, assignment, and function calls.
//main函数文件
#include "swap.h"
int main() {
int a = 100;
int b = 200;
swap(a, b);
return 0;
}
Running/Observing Results: This is a syntax or interface example, focus on the writing style; run and verify after incorporating it into a complete program.
Organization of Header Files
Purpose of header files: Header files contain external declarations of functions and variables for a library, making it convenient for us to call the library's APIs.
Notes:
- Common header files: stdio.h, stdlib.h, iostream, string, etc.
- Header file extensions: .h or .hpp. It's not necessary to include the extension, but it's recommended to do so.
- Preprocessing: #include <> and #include " "
- Conditional compilation
extern "C" { }is used to enable mixed compilation of C and C++ code, indicating that the code should be compiled and linked according to C-style compilation and linking conventions, rather than C++ conventions.
#ifndef __FILE_NAME_H_ //头文件防止引用重复的条件编译
#define __FILE_NAME_H_ //头文件防止引用重复的条件编译
#ifdef __cplusplus //混合编译的条件编译
extern "C" //混合编译的条件编译
{ //混合编译的条件编译
#endif //混合编译的条件编译
/* 头文件内容开始 */
//头文件内容:预处理、函数声明、变量声明
/* 头文件内容结束 */
#ifdef __cplusplus //混合编译的条件编译
} //混合编译的条件编译
#endif //混合编译的条件编译
#endif //头文件防止引用重复的条件编译
Running/Observing Results: This is a syntax or interface example, focus on the writing style; run and verify after incorporating it into a complete program.