Introduction to C

Learning C is like learning to drive a manual car — it's harder to pick up than an automatic, but once you master it, you gain precise control over every gear and truly understand how the machine works.

What Is C

C was created in 1972 by Dennis Ritchie at Bell Labs to develop the UNIX operating system. It is a general-purpose, procedural programming language that combines the structured expressiveness of high-level languages with the direct hardware control of low-level languages.

Simply put, C is a bridge between the programmer and computer hardware. You write code in human-readable syntax, and the C compiler translates it into instructions the machine can execute.

The Origins of C

Before C, operating systems were primarily written in assembly language. Assembly maps directly to CPU instructions — the resulting programs are fast, but poorly readable and non-portable. Switch to a different CPU, and you have to rewrite everything.

Dennis Ritchie was developing the UNIX operating system at the time and needed a tool that could manipulate hardware as efficiently as assembly while offering the readability and portability of a high-level language. C was born from that need.

C's family tree looks like this:

TEXT
ALGOL 60 (1960)
  → BCPL (1967, Martin Richards)
    → B (1970, Ken Thompson)
      → C (1972, Dennis Ritchie)

B was C's predecessor, but it was too limited — it only had one data type (word), which couldn't meet the demands of UNIX development. Ritchie built on B by adding a type system and more features, ultimately creating C.

The Symbiotic Relationship Between C and UNIX

C and UNIX made each other successful: once UNIX was rewritten in C, it became portable; and C spread widely because of UNIX's popularity. This symbiotic relationship is one of the key reasons for C's success. Even today, the Linux kernel (a UNIX derivative) is still written entirely in C — which is perhaps the best proof of C's capability.

Why Learn C

You might wonder: with so many "easy-to-use" languages like Python and JavaScript, why bother with C?

💡 Tip: The point of learning C isn't to build websites — it's to gain the low-level literacy to understand how everything works under the hood.

What Can C Do

C's application domains are far broader than you might think:

Domain Notable Projects
Operating Systems Linux, Windows kernel, macOS kernel
Embedded Systems Smartwatch firmware, automotive ECUs, IoT devices
Databases MySQL, PostgreSQL, SQLite
Game Engines Unreal Engine core, id Tech series
Compilers & Interpreters GCC, CPython, Lua
Network Infrastructure Nginx, Redis, Memcached
Graphics & Image Processing ImageMagick, OpenCV core modules

Notice a pattern? Systems that "must run fast and must not crash" almost always choose C.

C's Role in Different Domains

Operating Systems: The Linux kernel contains over 28 million lines of C code, and the Windows kernel's core is also C. An operating system needs to talk directly to hardware — managing memory, scheduling processes, handling interrupts. Only C (or assembly) can do this.

Embedded Systems: The smartwatch on your wrist, the router in your home, the ECU in your car — these devices have extremely limited resources (maybe just tens of KB of memory). Only C can make efficient use of every byte. Arduino programming is essentially C.

Databases: MySQL, PostgreSQL, and SQLite — the three most widely used open-source databases worldwide — are all written in C. Databases demand extremely high I/O performance and precise memory control, making C the natural choice.

Game Engines: While game logic is often written in C++ or scripting languages, the engine's innermost layer — the rendering pipeline, physics simulation, memory allocation — is still implemented in C to ensure peak performance.

Network Infrastructure: Over 30% of websites worldwide run on Nginx, and Redis is the dominant force in caching. Both are C projects. Network services must handle massive numbers of concurrent connections, and C's performance advantage shines here.

Key Features of C

Efficiency

C compilers generate highly optimized machine code that runs almost as fast as hand-written assembly. There's no interpreter overhead like Python, and no virtual machine layer like Java.

Portability

The same C code can be compiled and run on different platforms (Windows, Linux, macOS, embedded) with only minor modifications. This is the famous "write once, tweak slightly, compile everywhere" philosophy.

Low-Level Control

C allows you to directly manipulate memory (via pointers), perform bitwise operations, and even embed inline assembly. You have maximum control over hardware — which also means you're responsible for managing memory allocation and deallocation yourself.

Compact and Minimal

C has only 32 keywords (C89 standard), and its syntax is quite lean. It delegates many capabilities to the standard library rather than building them into the language itself, keeping the core simple.

⚠️ Note: This is a double-edged sword. C gives you unlimited freedom, but also hands you all the responsibility. There's no automatic garbage collection, no array bounds checking, no null pointer protection — the compiler won't stop you from making mistakes, but your program may crash at runtime.

The Standard Library

Another hallmark of C is its "small language, large standard library" design. The language itself provides only the most basic control structures and data types, while functionality like input/output, math operations, and string handling is provided by the standard library.

Core C standard library headers include:

Header Purpose Common Functions
<stdio.h> Input/Output printf, scanf, fopen, fclose
<stdlib.h> General Utilities malloc, free, exit, atoi
<string.h> String Operations strlen, strcpy, strcmp, strcat
<math.h> Math Functions sqrt, sin, cos, pow
<ctype.h> Character Classification isdigit, isalpha, toupper
<time.h> Time Handling time, clock, strftime

The standard library makes C "batteries included" — you can accomplish most common tasks without installing any third-party packages.

History of C

C didn't appear out of thin air — it has a clear evolutionary path:

Year Version Alias Key Features
1972 K&R C Designed by Dennis Ritchie; defined by The C Programming Language by Kernighan & Ritchie
1989 C89 ANSI C / C90 First official standard; defined the standard library, function prototypes, etc.
1999 C99 Introduced // comments, inline, variable-length arrays, long long, <stdbool.h>
2011 C11 Introduced _Generic, _Static_assert, atomic operations, multithreading support
2018 C17 Primarily bug fixes; no major new features
2023 C23 Introduced nullptr, true/false as keywords, decimal floating-point numbers
🔥 Common Mistake: For beginners, C99 is all you need. It has great compatibility and sufficient features, and most compilers and textbooks are based on it. You can explore C11/C17 features later as needed.

Why Standards Matter

Why does C need a standard? Imagine a world without one: every compiler implements C its own way — code that compiles fine on Windows might completely fail on Linux. Standards ensure code portability.

ANSI C (C89) was the first C standard. It unified the divergent behaviors of various compilers and defined the standard library interface. From C89 onward, C had a "correct answer" — programmers could confidently write code to the standard without worrying about compiler compatibility.

The Compiler Ecosystem

C has several mature compiler implementations:

Compiler Developer Platform Characteristics
GCC GNU Project All platforms Most popular open-source compiler
Clang LLVM Project All platforms Friendly error messages, fast compilation
MSVC Microsoft Windows Built into Visual Studio
ICC Intel All platforms Excellent optimization on Intel CPUs

Different compilers should behave the same for standard C code (guaranteed by the standard), but support for non-standard extensions varies. GCC or Clang is fine for beginners.

C vs. Other Languages

Feature C C++ Java Python
Execution Compiled to machine code Compiled to machine code Compiled to bytecode + JIT Interpreted
Speed Extremely fast Extremely fast Fast Slow
Memory Management Manual (malloc/free) Manual + optional auto (new/delete/RAII) Automatic GC Automatic GC
Pointer Support Full Full No native pointers No native pointers
Object-Oriented Not supported Supported Mandatory OOP Multi-paradigm
Learning Difficulty Medium High Medium Low
Typical Use Systems/embedded Games/desktop apps Enterprise backend/Android Data analysis/AI/scripting

As the table shows, C has an absolute advantage in speed and low-level control, but is relatively weaker in development efficiency and safety. This isn't a flaw — it's a design philosophy. C trusts the programmer to know what they're doing.

The Relationship Between C and C++

C++ is (almost) a superset of C, adding object-oriented programming, templates, exception handling, and the STL on top of C. Many people mistakenly think C++ is an "upgrade" to C, but the two have fundamentally different design philosophies:

Choosing between C and C++ depends on your project. Writing an OS kernel, drivers, or embedded firmware? Choose C. Building large desktop software, game logic, or high-performance services? Choose C++.

When Not to Use C

C isn't the right tool for everything. These scenarios have better alternatives:

Scenario Better Choice Reason
Web Frontend JavaScript Browsers only support JS
Data Analysis / ML Python Rich ecosystem, extensive libraries
Android Apps Kotlin Google's official recommendation
iOS Apps Swift Apple's official recommendation
Rapid Prototyping Python / Ruby High development speed
Safety-Critical Systems Rust Memory safety guarantees

Choosing a programming language is like choosing a tool — a hammer is great, but you shouldn't use it to turn a screw.

What a C Program Looks Like

Before diving into syntax, let's take a quick look at a C program:

C
#include <stdio.h>

int main(void) {
    printf("Hello, World!\n");
    return 0;
}

This program prints Hello, World! on the screen. You don't need to understand every line yet — later chapters will break them all down. For now, just know:

Compiled vs. Interpreted Languages

C is a compiled language, which is fundamentally different from interpreted languages like Python:

Aspect Compiled (C) Interpreted (Python)
Execution Compile to machine code first, then run Interpret and execute line by line
Speed Fast (direct machine code execution) Slow (interpreter overhead)
Error Detection Syntax errors caught at compile time Errors only surface at runtime
Cross-platform Compile separately for each platform Same code runs anywhere with an interpreter
Distribution Only need to ship the executable Target machine must have an interpreter installed

The advantage of compiled languages is that the compiler can catch many errors during compilation, rather than letting them surface only when the program runs. This is one reason C programs tend to be reliable.

How to Master C

Here are some practical tips for beginners:

  1. Write code by hand: Reading alone isn't learning. Type out and run every concept yourself.
  2. Understand, don't memorize: Syntax can be looked up, but the memory model and pointer logic must be understood deeply.
  3. Embrace errors: Compile errors and runtime errors are your best teachers. Learning to read error messages is a core skill.
  4. Build step by step: Learn to walk (basic syntax) before you run (pointers, memory management). Don't skip ahead.
  5. Read good code: Studying open-source projects (like the Redis source code) is a shortcut to leveling up.
TEXT
Basic Syntax → Variables & Types → Operators → Conditionals & Loops → Functions
    → Arrays → Pointers → Strings → Structs → File I/O
    → Dynamic Memory → Linked Lists/Stacks/Queues → Project Practice

Don't skip stages. Every topic before pointers needs to be solid, because pointers require the combined application of everything that comes before.

Resource Type Highlights
C Primer Plus Book Beginner-friendly, thorough explanations
The C Programming Language (K&R) Book Written by C's creators; concise classic
C Traps and Pitfalls Book Essential for intermediate learners; pitfall guide
CPP Reference (cppreference.com) Website Most authoritative C standard library reference
Learn C (learn-c.org) Website Interactive online tutorial

❓ FAQ

Q Is C outdated? Do I still need to learn it?
A Not at all. The Linux kernel, databases, and embedded systems still rely heavily on C. C consistently ranks in the top 3 on the TIOBE index and was #1 or #2 in 2024. The purpose of learning C is to understand low-level computing — that need will never go away.
Q Should I learn C or C++ first?
A Start with C. C++ extends C, so learning C first makes picking up C++ much easier. Jumping straight into C++ means facing OOP, templates, and the STL all at once, which can be overwhelming.
Q Do I need strong math skills to learn C?
A No. The basics only require middle-school math (addition, subtraction, multiplication, division, modulo). Advanced math is only needed for algorithm work, which is a separate topic.
Q Can C be used to build websites or mobile apps?
A Not really. C is mainly for systems programming. Websites use JavaScript/HTML/CSS, and mobile apps use Swift/Kotlin/Flutter. However, the server side of websites and the low-level core of mobile operating systems are often written in C.

📖 Summary

📝 Exercises

  1. List 3 software programs or devices you use daily, consider whether their low-level core might be powered by C, and explain your reasoning
  2. Compare C and Python in terms of "memory management" — describe the pros and cons of each in your own words
  3. Research the C23 standard and find one new feature that interests you; briefly describe what it does
100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏