C语言从入门到精通:全面指南与实战案例
一、C语言基础概述
1.1 C语言简介
C语言于1972年由Dennis Ritchie在贝尔实验室开发,是系统编程和底层开发的理想选择。其特点包括:
- 高效性:直接操作硬件资源
- 可移植性:符合ANSI C标准的程序可在多种平台运行
- 结构化编程:支持函数和模块化设计
- 中级语言:兼具高级语言的易用性和汇编语言的灵活性
1.2 开发环境配置
推荐开发工具:
- Windows:MinGW + VSCode
- Linux:GCC + Vim
- 跨平台IDE:Code::Blocks, Eclipse CDT
- // 第一个C程序:hello.c
- #include <stdio.h> // 标准输入输出头文件
- int main() {
-
- // 程序入口函数
- printf("Hello, World!\n"); // 输出函数
- return 0; // 返回状态码
- }
复制代码
编译运行命令: - gcc hello.c -o hello # 编译
- ./hello # 运行
复制代码
二、核心语法详解
2.1 数据类型与变量 - #include <stdio.h>
- #include <limits.h>
- int main() {
-
-
- // 基本数据类型
- char c = 'A'; // 字符型,1字节
- short s = 100; // 短整型,2字节
- int i = 1000; // 整型,4字节
- long l = 100000L; // 长整型,4或8字节
- float f = 3.14f; // 单精度浮点,4字节
- double d = 3.1415926535; // 双精度浮点,8字节
-
- // 类型限定符
- unsigned int ui = 4000000000; // 无符号整型
- const double PI = 3.14159; // 常量
-
- // 打印类型大小
- printf("Size of char: %zu bytes\n", sizeof(c));
- printf("INT_MAX: %d\n", INT_MAX);
-
- return 0;
- }
复制代码
2.2 运算符与表达式 - #include <stdio.h>
- int main() {
-
-
- int a = 10, b = 3;
-
- // 算术运算符
- printf("%d + %d = %d\n", a, b, a + b);
- printf("%d %% %d = %d\n", a, b, a % b); // 取模运算
-
- // 关系运算符
- printf("%d > %d: %d\n", a, b, a > b);
-
- // 逻辑运算符
- printf("!(%d > %d): %d\n", a, b, !(a > b));
-
- // 位运算符
- printf("%d << 2 = %d\n", a, a << 2); // 左移
-
- // 三目运算符
- int max = (a > b) ? a : b;
- printf("Max: %d\n", max);
-
- return 0;
- }
复制代码
2.3 控制结构 - #include <stdio.h>
- int main() {
-
-
- // if-else 语句
- int score = 85;
- if (score >= 90) {
-
-
- printf("A\n");
- } else if (score >= 80) {
-
-
- printf("B\n"); // 输出B
- } else {
-
-
- printf("C\n");
- }
- // switch 语句
- char grade = 'B';
- switch (grade) {
-
-
- case 'A': printf("Excellent!\n"); break;
- case 'B': printf("Good!\n"); break; // 输出Good!
- default: printf("Invalid grade\n");
- }
- // 循环结构
- // for 循环
- printf("For loop: ");
- for (int i = 0; i < 5; i++) {
-
-
- printf("%d ", i); // 输出0 1 2 3 4
- }
-
- // while 循环
- printf("\nWhile loop: ");
- int j = 5;
- while (j > 0) {
-
-
- printf("%d ", j--); // 输出5 4 3 2 1
- }
-
- // do-while 循环
- printf("\nDo-while loop: ");
- int k = 0;
- do {
-
-
- printf("%d ", k++); // 输出0 1 2 3 4
- } while (k < 5);
-
- return 0;
- }
复制代码
三、函数与模块化编程
3.1 函数定义与使用 - #include <stdio.h>
- // 函数声明
- int add(int a, int b);
- // 主函数
- int main() {
-
-
- int result = add(5, 3);
- printf("5 + 3 = %d\n", result); // 输出8
- return 0;
- }
- // 函数定义
- int add(int a, int b) {
-
-
- return a + b;
- }
复制代码
3.2 递归函数 - #include <stdio.h>
- // 递归计算阶乘
- long factorial(int n) {
-
-
- if (n == 0 || n == 1)
- return 1;
- else
- return n * factorial
复制代码 |