
C基础概述C是一种通用的、面向对象的编程语言由Bjarne Stroustrup于1985年开发。它是C语言的扩展增加了面向对象编程OOP特性同时保留了C的高效性和灵活性。C广泛应用于系统开发、游戏开发、嵌入式系统和高性能计算等领域。基本语法结构C程序由函数、变量、语句和表达式组成。每个C程序必须包含一个main函数作为程序的入口点。以下是一个简单的C程序示例#include iostream using namespace std; int main() { cout Hello, World! endl; return 0; }#include iostream引入输入输出流库。using namespace std使用标准命名空间避免重复写std::。cout Hello, World! endl输出字符串并换行。return 0表示程序正常结束。数据类型与变量C支持多种数据类型包括基本类型和用户自定义类型。基本数据类型分为以下几类整型int、short、long、long long。浮点型float、double、long double。字符型char、wchar_t。布尔型bool值为true或false。变量声明语法int age 25; float price 99.99; char grade A; bool isStudent true;运算符C支持多种运算符包括算术、关系、逻辑、位运算等。算术运算符、-、*、/、%。关系运算符、!、、、、。逻辑运算符与、||或、!非。赋值运算符、、-、*、/。控制结构C提供多种控制结构来控制程序流程。条件语句if (condition) { // 代码块 } else if (another_condition) { // 代码块 } else { // 代码块 }循环语句for (int i 0; i 10; i) { // 代码块 } while (condition) { // 代码块 } do { // 代码块 } while (condition);函数函数是一段可重复使用的代码块用于执行特定任务。函数定义包括返回类型、函数名、参数列表和函数体。int add(int a, int b) { return a b; }调用函数int result add(5, 3); // result 8数组与字符串数组是相同类型元素的集合存储在连续内存中。int numbers[5] {1, 2, 3, 4, 5};字符串是字符数组C提供了string类简化字符串操作。#include string string name Alice;指针与引用指针是存储内存地址的变量引用是变量的别名。int x 10; int *ptr x; // 指针 int ref x; // 引用面向对象编程C支持面向对象编程包括类、对象、继承、多态等特性。类与对象class Person { private: string name; int age; public: void setName(string n) { name n; } string getName() { return name; } }; Person p; p.setName(Bob); cout p.getName(); // 输出 Bob继承class Student : public Person { private: int grade; public: void setGrade(int g) { grade g; } };文件操作C使用fstream库进行文件读写操作。#include fstream ofstream outFile(example.txt); outFile Hello, File!; outFile.close();异常处理C通过try、catch和throw实现异常处理。try { throw runtime_error(Error occurred); } catch (runtime_error e) { cout e.what(); }标准模板库STLSTL提供了一系列模板类和函数如容器、算法和迭代器。容器示例#include vector vectorint vec {1, 2, 3}; vec.push_back(4);算法示例#include algorithm sort(vec.begin(), vec.end());总结C是一门功能强大且灵活的语言适合开发高性能和复杂的应用程序。掌握基础语法、数据类型、控制结构、函数和面向对象编程是学习C的关键。通过实践和项目经验可以逐步深入理解C的高级特性和最佳实践。