Usage of flag in C language: Program control: represents true/false status, used to control program flow based on conditions. Status indicator: Indicates a specific status, such as whether it is registered. Error handling: Used to handle errors, such as returning an error code when a file fails to open. Parameter passing: Indicates optional parameters, used to modify function behavior.
Usage examples of flag in C language
flag is a widely used variable type in C language, representing A Boolean value (true or false). It is often used to control program flow or indicate a specific status. Here are some common usage examples of flag:
As a program control
<code class="c">int main() { int flag = 0; // 初始化为假 // 当满足某个条件时,将 flag 设置为真 if (condition) { flag = 1; } // 根据 flag 的值执行不同的操作 if (flag) { // 条件为真时执行的代码 } else { // 条件为假时执行的代码 } return 0; }</code>
As a status indicator
<code class="c">struct student { int id; char name[50]; int enrolled; // 0: 未注册,1: 已注册 }; void register_student(struct student *student) { student->enrolled = 1; } int is_student_enrolled(struct student *student) { return student->enrolled; }</code>
Handling as error
<code class="c">int open_file(const char *filename) { FILE *file; file = fopen(filename, "r"); if (!file) { return -1; // 返回错误代码 } return file; } int main() { FILE *file = open_file("myfile.txt"); if (file == -1) { // 处理文件打开错误 } // 使用 file 指针读取文件内容 fclose(file); return 0; }</code>
Passed as parameter
<code class="c">void print_array(int arr[], int size, int reverse) { if (reverse) { for (int i = size - 1; i >= 0; i--) { printf("%d ", arr[i]); } } else { for (int i = 0; i < size; i++) { printf("%d ", arr[i]); } } } int main() { int arr[] = {1, 2, 3, 4, 5}; int size = sizeof(arr) / sizeof(arr[0]); print_array(arr, size, 0); // 正序打印数组 print_array(arr, size, 1); // 倒序打印数组 return 0; }</code>
The above is the detailed content of Examples of flag usage in C language. For more information, please follow other related articles on the PHP Chinese website!