📘 Chapter 1 🟢 Beginner ⏱ 30–45 min

Introduction to C Language

From Bell Labs in 1972 to powering every microcontroller on the planet — a complete foundation in the language that runs the world’s hardware.

🎯 Learning Objectives
Explain what C is and why it was created
Trace the complete history of C
List all major features of C
Understand the full compilation pipeline
Write and explain a first C program
Use printf, scanf, tokens, and variables
1Introduction

What is C?

C is a general-purpose, procedural, compiled programming language developed for writing efficient and portable software. It enables programmers to communicate with a computer using human-readable instructions that are then translated into machine code the hardware executes directly.

Unlike natural languages, computers understand only binary — sequences of 0s and 1s. C acts as a precise bridge: you write instructions a human can read, and the compiler converts them into instructions a machine can run.

💡
Simple Definition
C is a language that lets humans tell computers exactly what to do — step by step, with full control over memory and hardware.

Instead of writing raw binary:

Binary
010010010101010100110010...

You write readable C code:

C
printf("Hello");

The compiler automatically converts your C source code into machine-executable instructions.

Why Learn C?

Many of the most important modern programming languages were directly influenced by or built upon C. Learning C means understanding the shared foundation they all rest on.

C++

Extends C with object-oriented programming. Used in game engines, operating systems, and embedded systems.

Java

Syntax heavily inspired by C. Runs on billions of devices from Android phones to bank servers.

🎯

C# & Go

Microsoft’s C# and Google’s Go both borrowed their syntax and philosophy directly from C.

🦀

Rust

The modern systems language. C-inspired syntax, designed to solve C’s memory safety challenges.

🐍

Python

CPython, the most popular Python interpreter, is written entirely in C for maximum performance.

📱

Objective-C

The original language behind Apple’s software. A strict superset of the C language.

Key Takeaway
Even today, C is among the most important programming languages ever created. It runs operating systems, firmware, microcontrollers, and the infrastructure of the modern internet.
2Origin

Why Was C Created?

Before C existed, programmers who needed control over hardware had to write software directly in Assembly Language — machine-specific low-level instructions:

Assembly (x86)
MOV AX, 5
ADD AX, 10
MOV [result], AX

Assembly language was powerful but came with serious problems that limited what programmers could realistically accomplish:

✓ Assembly Strengths
  • Extremely fast execution
  • Direct hardware control
  • Precise memory access
  • Minimal overhead
✗ Assembly Weaknesses
  • Extremely difficult to write
  • Different for every processor
  • Nearly impossible to maintain
  • Not portable between machines

Programmers needed a new language that combined the best of both worlds:

  • Easier to write than Assembly Language
  • Faster than existing high-level languages like FORTRAN or COBOL
  • Portable across different hardware architectures
  • Efficient enough to write a complete operating system
Machine Language 01001000 11000101 ● Impossible to read led to Assembly Language MOV AX, 5 ● Still very hard solution C Language printf("Hello"); ✓ Human-readable ✓ Portable & Fast 1972 — Bell Labs

The evolution from unreadable machine code to Assembly to C — each step made programming more accessible and powerful

C Solved All the Problems
C was easier than Assembly, faster than other high-level languages, portable across processors, and powerful enough to rewrite the entire UNIX operating system.
3History

History of C

Timeline

1966
BCPL Developed
Martin Richards at Cambridge develops BCPL (Basic Combined Programming Language), a typeless systems language that pioneered many ideas C would later adopt.
1969
B Language Created
Ken Thompson at Bell Labs creates B, directly inspired by BCPL, to write early versions of UNIX on the PDP-7. B was also typeless.
1972
C Language Born 📅
Dennis Ritchie at Bell Labs develops C by adding data types, structures, and improved features to B. C was designed specifically to rewrite UNIX.
1973
UNIX Rewritten in C
The UNIX operating system is successfully rewritten in C. This was a landmark — for the first time, a complete OS was portable across different machines.
1978
The C Programming Language Book
Brian Kernighan and Dennis Ritchie publish "The C Programming Language" (K&R C), which becomes the de facto standard for a decade.
1989
ANSI C Standard (C89)
ANSI formally standardizes C, ending years of dialect fragmentation. Also called C89 or ANSI C, this is still the baseline for portable C code.
1999
C99 Standard
Major update adding inline functions, new data types (long long int), variable-length arrays, and the // single-line comment.
2011
C11 Standard
Adds multi-threading support, anonymous structures/unions, improved Unicode support, and atomic operations for embedded and concurrent programming.
2018
C17 Standard
A maintenance release clarifying defects in C11 without adding major new features. The current stable widely-supported standard.
2023
C23 Standard
The latest standard adding new keywords (true, false, nullptr), improvements to type inference, enhanced preprocessor features, and more.

Dennis Ritchie — Creator of C

Dennis Ritchie developed C at Bell Laboratories in New Jersey. His primary motivation was to rewrite the UNIX operating system in a language that was simultaneously efficient and portable. Before C, operating systems were written entirely in Assembly Language, which meant rewriting them from scratch for every new processor architecture.

Ritchie’s decision to write UNIX in C changed computer science permanently. It proved that a high-level language could produce code efficient enough for systems programming, a belief that had previously been considered impossible.

📚
Historical Note
Dennis Ritchie and Ken Thompson were jointly awarded the Turing Award in 1983 for their development of generic operating systems theory and specifically for the implementation of the UNIX operating system.

Language Evolution

BCPL 1966 — M. Richards B Language 1969 — K. Thompson C Language 1972 — D. Ritchie C++ 1985 — Stroustrup Objective-C 1984 — Cox Java / C# influenced Go / Rust inspired by

Evolution from BCPL (1966) to B (1969) to C (1972). C directly spawned C++ and Objective-C, and heavily influenced nearly every modern language.

4Language Profile

Features of C

C became the dominant systems programming language because of a unique combination of features. Each one addresses a specific engineering need.

📈

Simple

C has a small, focused keyword set compared to modern languages. The syntax is clean and easy to learn. Even complex programs follow predictable patterns.

Fast

C compiles directly to native machine code with minimal abstraction overhead. This is why operating systems and real-time embedded systems are written in C.

🌎

Portable

A C program written on Windows typically needs little or no modification to compile and run on Linux, macOS, or an ARM microcontroller.

🏗

Structured

Programs are organized into functions. Each function is a self-contained unit with clear inputs and outputs, improving readability and maintainability.

🧷

Modular

Large programs are broken into smaller modules — separate .c files. Each module can be written, tested, and debugged independently.

🧮

Middle-Level

C combines high-level constructs (functions, loops, if/else) with low-level capabilities (direct memory access, pointer arithmetic, bit manipulation).

💾

Efficient Memory

Programmers control exactly how memory is allocated, used, and freed. There is no hidden garbage collector consuming resources in the background.

🔨

Extensible

C programs can call assembly routines for hardware-critical operations. The language can be extended with external libraries and standard headers.

Middle-Level Language: The Sweet Spot

One of C’s defining characteristics is that it sits between low-level Assembly and high-level languages like Python. This gives it a unique combination of power and accessibility:

High-Level Capability
  • Human-readable syntax
  • Functions and structured code
  • Standard library functions
  • Portable across platforms
Low-Level Capability
  • Direct memory access via pointers
  • Hardware register access
  • Bit-level manipulation
  • Manual memory management
C — High-level capability
printf("Hello, World!");
C — Low-level capability (hardware register)
int *ptr = (int *)0x40021000;  /* Access hardware register directly */
*ptr = 0xFF;                   /* Write to hardware */
5Language Profile

Applications of C

C is used almost everywhere that performance, reliability, or hardware control is required. Here are the major domains where C is irreplaceable:

💻
Operating Systems
Linux Kernel, Windows NT Core, UNIX, macOS kernel (XNU)
🔌
Embedded Systems
Washing machines, microwaves, smart TVs, AC controllers, automotive ECUs
🌐
Networking
Routers, switches, network drivers, TCP/IP stack implementations
💾
Device Drivers
USB drivers, graphics drivers, storage controllers, peripheral interfaces
🎮
Game Engines
Performance-critical game engine cores, physics engines, graphics APIs
🔬
Scientific Computing
Numerical libraries (BLAS, LAPACK), simulation software, signal processing
🗃
Database Systems
MySQL, SQLite, PostgreSQL core engines are written in C
🔧
Compilers
GCC (GNU Compiler Collection), the original CLANG front-end, TinyCC

Real-World Examples

Device / SystemUses C?What C Powers
ATM Machine✅ YesTransaction logic, hardware interface, secure I/O
Car ECU (Engine Control Unit)✅ YesReal-time sensor processing, fuel injection control
Arduino (Libraries)✅ YesCore libraries, hardware abstraction layer
Linux Kernel✅ YesEntirely written in C (~99.9%)
Printer Firmware✅ YesPrint queue management, hardware control
Drone Flight Controller✅ YesPID algorithms, sensor fusion, real-time control
Medical Devices (pacemakers)✅ YesSafety-critical real-time embedded firmware
Satellite Software✅ YesGuidance systems, telemetry, reliable low-overhead code
💡
Why Embedded Systems Love C
Embedded systems have constrained resources (kilobytes of RAM, limited CPU). C programs are tiny, fast, and allow programmers to control exactly how much memory and CPU time each operation uses.
6Language Profile

Advantages & Disadvantages

Every language is a set of tradeoffs. Understanding C’s strengths and weaknesses helps you decide when to use it and what pitfalls to watch for.

✅ Advantages of C
  • Very fast execution speed
  • Highly portable across platforms
  • Small runtime footprint
  • Highly efficient memory use
  • Direct hardware and memory access
  • Large mature ecosystem of libraries
  • Ideal for embedded systems
  • Foundation for learning other languages
❌ Disadvantages of C
  • No garbage collection (manual memory management)
  • No built-in object-oriented programming
  • Weak type safety — easy to misuse pointers
  • Buffer overflow security vulnerabilities
  • Less abstraction than modern languages
  • Harder to debug complex memory issues
  • No built-in exception handling
  • Standard library is relatively minimal

Advantages vs Disadvantages (Comparison Table)

AdvantageCorresponding Disadvantage
Fast executionManual memory management required
Portable across platformsNo garbage collector — memory leaks possible
Efficient memory usagePointer-related bugs can be difficult to trace
Direct hardware accessBuffer overflow creates security vulnerabilities
Small executable sizeLess abstraction than Java, Python, or C#
C = Power + Responsibility

C gives you enormous power over the computer. It also expects you to use that power carefully. Every byte of memory you allocate, you must also free. Every pointer you use, you must make sure is valid.

Frequently Asked Questions

Is C still worth learning in 2024 and beyond?
Absolutely. C remains one of the most important programming languages. Operating systems, embedded systems, and firmware are still overwhelmingly written in C. It also gives you the deep understanding of how computers work that makes you a better programmer in any language.
Is C difficult to learn?
The basic syntax is easy and beginner-friendly. The challenging parts — pointers, memory management, and low-level programming — require practice and careful thinking, but are not beyond any motivated learner.
Is C an object-oriented language?
No. C is a procedural programming language. It organizes code into functions and procedures. If you need object-oriented features, C++ (which extends C) adds classes, inheritance, and polymorphism.
Why is C called a middle-level language?
Because C supports both high-level constructs (like functions, loops, if/else, and formatted I/O) and low-level capabilities (like pointer arithmetic, bit manipulation, and direct memory addressing). It bridges the gap between Assembly and purely high-level languages.
7How C Works

The Compilation Process

When you write C code and run it, several things happen behind the scenes. The source code you type cannot run directly — it goes through a multi-stage compilation pipeline that transforms it into a machine-executable program.

💡
How it works at a glance
You write human-readable C source code. The compiler transforms it into binary machine code. The computer executes that machine code at hardware speed.

The Four Stages

hello.c Source C code you write Preprocessor cpp Expands #include Expands #define Removes comments → hello.i Compiler cc / gcc Syntax checking Optimization C → Assembly → hello.s Assembler as Assembly → Machine code Binary object file → hello.o Linker ld Combines objects Links libraries (libc for printf) → ./hello ./hello Executable Machine code runs on CPU gcc hello.c -o hello GCC runs all four stages automatically when you compile

The four-stage C compilation pipeline. GCC runs all stages automatically with a single command.

Stage 1: Preprocessing

The preprocessor handles all lines starting with #. It copies the contents of header files into your source, expands macros (#define), removes all comments, and handles conditional compilation (#ifdef). The output is a larger, pure C file (.i extension).

Stage 2: Compilation

The compiler takes the preprocessed C code and translates it into assembly language — a human-readable form of the machine’s instruction set. This stage also performs syntax checking and optimization.

Stage 3: Assembly

The assembler converts assembly language into binary machine code (0s and 1s). The output is an object file (.o) that contains machine code but is not yet ready to run because it has unresolved references to library functions.

Stage 4: Linking

The linker combines your object file(s) with the necessary library code (like the C standard library that contains printf()). It resolves all external references and produces the final executable program.

⚠️
Important
When you call printf(), the declaration is in <stdio.h> (header file), but the actual compiled code for printf lives in the C standard library (libc). The linker connects them at link time.
8How C Works

Structure of a C Program

Every C program, no matter how large or complex, follows the same fundamental organizational structure. Think of these as the six layers that make up any C program:

Structure of a C Program 1. Documentation Section /* Program Name, Author, Date */ — Comments explaining the program 2. Link Section #include <stdio.h> — Include standard library header files 3. Definition Section #define PI 3.14 — Define constants and macros 4. Global Declaration Section int totalStudents = 100; — Variables accessible to all functions 5. main() Function int main() { ... return 0; } — Program entry point, execution starts here 6. User-Defined Functions int add(int a, int b) { return a + b; } — Helper functions called from main()

The six structural sections of a C program, in order from top to bottom

Here is the simplest complete C program that demonstrates this structure:

C — Complete Program Structure
/*
    Program Name : Hello World
    Author       : Student
    Date         : 2024
*/                              /* 1. Documentation Section */

#include <stdio.h>              /* 2. Link Section          */

#define MAX_SIZE 100            /* 3. Definition Section    */

int total = 0;                  /* 4. Global Declaration    */

int main()                      /* 5. main() Function       */
{
    printf("Hello, World!\n");
    return 0;
}

int add(int a, int b)           /* 6. User-defined Function */
{
    return a + b;
}
📚
Not All Sections Are Required
A minimal C program only needs the main() function with the appropriate header included. The other sections are used as your program grows in complexity.
9Syntax Basics

Documentation & Comments

The documentation section contains comments — text that is completely ignored by the compiler but is invaluable for human readers. Good comments explain why something is done, not just what.

Single-Line Comments

Use // to comment out everything from that point to the end of the line:

C
// This is a single-line comment

// Store student marks
marks = 95;

Multi-Line Comments

Use /* to start and */ to end a block comment. Useful for documentation blocks, explanations, and temporarily disabling code:

C
/*
    Program Name : Student Grade Calculator
    Author       : Naveen Kumar
    Date         : 2024-01-15
    Description  : Reads student marks and calculates grades
*/

/*
    This is
    a multi-line
    comment block.
*/

Writing Good Comments

Comments should add information that isn’t obvious from the code itself. Commenting what the code does (when it’s already clear) is noise. Commenting why adds real value:

✗ Bad Comment (states the obvious)
x = x + 1; // Increment x by 1
✓ Good Comment (explains intent)
// Retry communication after timeout retry++;
⚠️
Common Mistake
Multi-line comments cannot be nested in C. Writing /* outer /* inner */ still outer */ will cause a compiler error because the first */ closes the comment.
10Syntax Basics

Header Files & the Link Section

The line #include <stdio.h> tells the preprocessor to include a header file. Think of header files as toolboxes that contain declarations for useful functions and types you can use in your program.

💡
Analogy
Suppose you want to build a house. Instead of manufacturing your own hammer, saw, and drill, you borrow existing tools. Header files work the same way — they give you access to pre-built, pre-tested functions.
C
#include <stdio.h>    /* Standard Input/Output */
#include <stdlib.h>   /* General Utilities     */
#include <string.h>   /* String Functions      */
#include <math.h>     /* Mathematical Functions */

Common Header Files

Header FilePurposeKey Functions
stdio.hStandard Input/Outputprintf, scanf, fopen, fclose
stdlib.hGeneral Utilitiesmalloc, free, exit, atoi
string.hString Functionsstrlen, strcpy, strcmp, strcat
math.hMath Functionssqrt, pow, sin, cos, abs
ctype.hCharacter Handlingisalpha, isdigit, toupper, tolower
stdint.hFixed-Width Integer Typesint8_t, uint16_t, uint32_t
stdbool.hBoolean Typebool, true, false

Angle Brackets vs. Quotes

📑 System / Standard Library
#include <stdio.h>
📁 Your Own Header File
#include "myheader.h"
11Syntax Basics

Macros & the Definition Section

The definition section uses #define to create named constants and macros. Unlike variables, #define values are replaced textually by the preprocessor before compilation — they exist at zero runtime cost.

C
#define PI         3.14159
#define MAX_SIZE   100
#define TRUE       1
#define FALSE      0

When the compiler sees MAX_SIZE, it substitutes the value 100 directly. After preprocessing, the code looks like this:

Before Preprocessing
int arr[MAX_SIZE]; float area = PI * r * r;
After Preprocessing
int arr[100]; float area = 3.14159 * r * r;
Best Practice for Embedded Systems
In embedded C, #define is extensively used for hardware register addresses, bit masks, and configuration values. For example: #define LED_PORT 0x40020000
12Syntax Basics

Global Declaration Section

Variables declared outside all functions are called global variables. They can be accessed by any function in the same file (and with extern, across files).

C
#include <stdio.h>

int total = 10;          /* Global variable: accessible everywhere */

void printTotal()
{
    printf("Total: %d\n", total);   /* Can access 'total' */
}

int main()
{
    printf("%d\n", total);          /* Can also access 'total' */
    total = 20;                     /* Can modify it too */
    printTotal();                   /* Prints: Total: 20 */
    return 0;
}
⚠️
Use Globals With Care
Global variables make programs harder to reason about because any function can modify them. Prefer local variables (declared inside functions) when possible. In embedded systems, globals are sometimes necessary for sharing state between interrupt handlers and main code.
13Syntax Basics

The main() Function

Every standard C program must have exactly one main() function. This is the entry point — the operating system calls main() first when your program starts, regardless of how many other functions exist.

C
int main()
{
    return 0;
}

Anatomy of main()

PartMeaning
intThe function returns an integer value to the operating system
mainThe required name — the OS specifically looks for this name
()Parentheses indicate this is a function (can contain parameters)
{ }Curly braces define the function body — everything inside belongs to main()
return 0;Returns 0 to the OS, indicating successful program completion
💡
Return Values
By convention, returning 0 signals success to the OS. Returning any non-zero value signals an error. You can check this from the command line after running your program: echo $? on Linux/macOS.
14First Program

Your First C Program

Every programmer’s journey begins with Hello, World. Here is the complete, minimal C program:

C
#include <stdio.h>

int main()
{
    printf("Hello World");

    return 0;
}
Output
Hello World

Line-by-Line Explanation

LineCodeMeaning
1#include <stdio.h>Include the Standard Input/Output library so printf is available
2(blank line)Whitespace for readability — ignored by the compiler
3int main()Define the main function. Program execution begins here.
4{Open curly brace — begin the function body
5printf("Hello World");Call printf to display text on the screen
6return 0;Return 0 to the OS indicating successful completion
7}Close curly brace — end the function body
How to Compile & Run (Linux/macOS/WSL)
Save as hello.c, then run: gcc hello.c -o hello to compile, then ./hello to execute.
15First Program

The printf() Function

printf() (print formatted) is the primary output function in C. It displays text and values to the standard output (your terminal screen).

C — Basic Syntax
printf("Text to display");
printf("Value: %d", someVariable);
C — Multiple statements
printf("Hello");
printf("World");
Output
HelloWorld
⚠️
No Automatic Newline
printf() does not automatically move to the next line. You must explicitly use \n (the newline escape sequence) to break lines.
C — With newlines
printf("Hello\n");
printf("World");
Output
Hello World

Escape Sequences

Escape sequences are special character combinations that represent non-printable characters or special formatting:

\n
New Line
\t
Horizontal Tab
\\
Backslash
\"
Double Quote
\'
Single Quote
\r
Carriage Return
\0
Null Character
\a
Alert / Bell
C — Escape sequence example
printf("Name\tMarks\n");
printf("Alice\t95\n");
printf("Bob\t88\n");
Output
Name Marks Alice 95 Bob 88

Format Specifiers

When you want to print values stored in variables, you use format specifiers as placeholders inside the string:

%d
int (decimal)
printf("%d", 42);
%f
float / double
printf("%f", 3.14);
%c
char (character)
printf("%c", 'A');
%s
string
printf("%s", "Hi");
%lf
double (scanf)
scanf("%lf", &x);
%u
unsigned int
printf("%u", 42u);
%x
hexadecimal
printf("%x", 255);
%p
pointer address
printf("%p", ptr);
C — Format specifiers in action
#include <stdio.h>

int main()
{
    int age = 20;
    float gpa = 3.85;
    char grade = 'A';

    printf("Age:   %d\n",   age);
    printf("GPA:   %.2f\n", gpa);
    printf("Grade: %c\n",   grade);

    return 0;
}
Output
Age: 20 GPA: 3.85 Grade: A
16First Program

The scanf() Function

scanf() (scan formatted) reads input from the user via the keyboard. It pauses execution and waits for the user to type a value and press Enter.

C — Syntax
scanf("format_specifier", &variable);
C — Complete Example
#include <stdio.h>

int main()
{
    int age;

    printf("Enter your age: ");
    scanf("%d", &age);
    printf("Your age is: %d\n", age);

    return 0;
}
Input / Output
Enter your age: 20 Your age is: 20

Why the & (Ampersand)?

The & symbol is the address-of operator. It gives scanf() the memory address of the variable, not the variable’s current value. scanf() needs this address so it knows exactly where in memory to write the input value.

💡
Analogy
Imagine you want to send a letter. You need to know the address of the house, not just the person’s name. The & gives scanf the exact memory address where the value should be delivered.
⚠️
Important
Forgetting the & with scanf() is one of the most common beginner mistakes. Without it, your program may crash with a segmentation fault at runtime — the compiler often won’t warn you.

Reading Multiple Values

C
#include <stdio.h>

int main()
{
    int    age;
    float  marks;
    char   grade;

    printf("Enter age, marks, and grade: ");
    scanf("%d %f %c", &age, &marks, &grade);

    printf("Age: %d, Marks: %.1f, Grade: %c\n", age, marks, grade);

    return 0;
}
17First Program

Semicolons

In C, every statement must end with a semicolon (;). The semicolon is the statement terminator — it tells the compiler that a statement has ended. Think of it as the full stop (period) at the end of an English sentence.

✗ Wrong — Missing Semicolons
int x = 5 printf("Hello")
✓ Correct — Semicolons Present
int x = 5; printf("Hello");
Missing Semicolons = Compiler Error
Forgetting a semicolon is one of the most common beginner errors. The compiler will report an error on the next line (because it keeps reading until it finds one), which can be confusing at first.

Exceptions — these do NOT end with semicolons:

  • Preprocessor directives: #include <stdio.h>
  • Function definitions: int main() { ... }
  • Control flow blocks: if(...) { ... }, for(...) { ... }
18First Program

Case Sensitivity

C is a case-sensitive language. This means that uppercase and lowercase letters are treated as completely different characters. The following three are three different identifiers:

C
marks    /* identifier 1 */
Marks    /* identifier 2 */
MARKS    /* identifier 3 */
✗ Wrong — Wrong Case
Printf("Hello"); /* Capital P */ PRINTF("Hello"); /* All caps */ Scanf("%d", &x); /* Capital S */
✓ Correct — All Lowercase
printf("Hello"); /* Correct */ scanf("%d", &x); /* Correct */
Convention
By convention, all C keywords and standard library function names are lowercase. Variables typically use camelCase (like studentAge) or snake_case (like student_age). Constants defined with #define use ALL_CAPS.

Common Beginner Mistakes (Syntax)

MistakeWrong CodeCorrect Code
Forgetting semicolonsprintf("Hello")printf("Hello");
Missing header fileint main() { printf("Hi"); }#include <stdio.h> first
Wrong case for printfPrintf("Hello");printf("Hello");
Missing & in scanfscanf("%d", age);scanf("%d", &age);
19Tokens & Blocks

Tokens in C

Before the compiler can process your code, it must break it down into its smallest meaningful pieces. These pieces are called tokens.

📚
Definition
A token is the smallest meaningful unit in a C program that the compiler recognizes and can act upon. Just as words are the smallest units of meaning in English sentences, tokens are the smallest units of meaning in C programs.

Consider this English sentence: "I love programming." — the individual words I, love, programming are the meaningful units.

Similarly, when the C compiler sees int age = 20;, it breaks it into these tokens:

int age = 20 ;
Keyword
Identifier
Operator
Constant
Special Symbol

The Six Types of Tokens

Token TypeExamplesDescription
Keywordsint, if, while, returnReserved words with predefined meaning
Identifierssum, studentAge, mainNames you give to variables, functions, etc.
Constants10, 3.14, 'A'Literal values that don’t change
String Literals"Hello", "C Programming"Sequences of characters in double quotes
Operators+, -, *, =, ==Symbols that perform operations
Special Symbols( ), { }, ;, [ ], ,Punctuation with structural meaning
K I C S O S
KKeywords
IIdentifiers
CConstants
SStrings
OOperators
SSymbols
“Kind Intelligent Cats Sing Opera Softly.”
20Tokens & Blocks

Keywords

Keywords are reserved words that already have a fixed, predefined meaning in the C language. The compiler uses them to understand program structure. You cannot use them as variable names or identifiers.

C — Error example
int int = 10;     /* Error: "int" is a keyword */
int while = 5;    /* Error: "while" is a keyword */
C — Correct
int number = 10;   /* Correct: "number" is a valid identifier */
int count = 5;     /* Correct: "count" is a valid identifier */

Common C Keywords

intInteger type
floatFloat type
charCharacter type
doubleDouble precision
voidNo return value
ifDecision making
elseAlternative branch
whileLoop
forCount-controlled loop
doDo-while loop
breakExit loop/switch
continueSkip iteration
returnReturn from function
switchMulti-way selection
caseSwitch option
defaultDefault case
structStructure type
typedefType alias
constConstant
staticStatic storage
externExternal linkage
sizeofSize in bytes
unsignedNo sign bit
signedWith sign bit
💡
How Many Keywords?
Standard C (C11) has 44 keywords. C23 adds a few more. This is far fewer than most modern languages, contributing to C’s simplicity and learnability.
21Tokens & Blocks

Identifiers

Identifiers are names that you create to identify variables, functions, arrays, structures, and other user-defined elements in your program.

C — Examples of Identifiers
age
marks
studentName
totalSalary
calculateAverage

Rules for Naming Identifiers

There are exactly five rules. Violating any one of them causes a compiler error:

1
Valid Characters

Can contain letters (A-Z, a-z), digits (0-9), and underscore (_). No other characters allowed.

2
Cannot Start with a Digit

student1 is valid. 1student is not. Must begin with a letter or underscore.

3
No Spaces Allowed

studentMarks is valid. student marks is not. Use camelCase or snake_case instead.

4
Keywords Forbidden

int while = 5; is illegal. Reserved words cannot be used as identifiers.

5
C is Case-Sensitive

marks, Marks, and MARKS are three completely different identifiers.

Good Naming Style

Meaningful names make your code self-documenting and dramatically easier to maintain:

✗ Bad (cryptic names)
int a; float b; char x;
✓ Good (descriptive names)
int studentAge; float examScore; char studentGrade;
IdentifierValid?Reason
studentLetters only — valid
student1Letters and digit — valid
_countStarts with underscore — valid
1studentStarts with digit — invalid
student marksContains space — invalid
whileIs a keyword — reserved
my-varHyphen not allowed — invalid
22Tokens & Blocks

Variables

A variable is a named memory location that stores data. You give the memory location a name (the variable name) so you can refer to it in your program. When the value changes, the contents of that memory location change.

int age = 20;
age
20
int • 4 bytes
The name age labels
a location in RAM
holding the value 20

Variable Declaration

Before using a variable you must declare it — tell the compiler its name and data type:

C — Syntax
datatype variableName;
C — Examples
int    age;         /* declare an integer variable */
float  salary;      /* declare a float variable    */
char   grade;       /* declare a character variable */
double pi;          /* declare a double variable   */

Initialization

Giving a variable its first value is called initialization. It can be done at declaration or separately:

C
/* Declaration only */
int age;

/* Initialization after declaration */
age = 20;

/* Declaration AND initialization in one line */
int score = 95;

Declaration vs Initialization

OperationCodeWhat happens
Declarationint age;Creates the variable; value is undefined (garbage)
Initializationage = 20;Assigns the first value to an existing variable
Combinedint age = 20;Declares and initializes in one step

Multiple Variables

C — Multiple declarations
/* Separate declarations */
int a = 10;
int b = 20;
int c = 30;

/* Combined on one line */
int a = 10, b = 20, c = 30;
Best Practice: Always Initialize
Declaring a variable without initializing it leaves it with a garbage (undefined) value. In embedded systems, this can cause unpredictable hardware behavior. Always initialize: int count = 0;
23Tokens & Blocks

Constants

A constant is a value that cannot be changed during program execution. Once defined, it remains fixed for the program’s lifetime. Attempting to modify a const variable causes a compiler error.

C
const float PI = 3.14159;
const int   MAX = 100;

PI = 5;     /* ERROR: cannot modify a const variable */
MAX = 200;  /* ERROR: cannot modify a const variable */

Types of Constants

🔢

Integer Constants

Whole numbers without decimal points: 10, 200, -15, 0

🔣

Floating Constants

Numbers with decimal points: 3.14, 5.67, 100.25, -0.5

🔠

Character Constants

Single characters in single quotes: 'A', 'Z', '9', '$'

💬

String Constants

Characters in double quotes: "Hello", "C Programming", "Embedded"

C — All constant types
/* Integer constant */
const int MAX_STUDENTS = 50;

/* Floating constant */
const float PI = 3.14159;

/* Character constant */
const char PASS_GRADE = 'A';

/* String constant (stored as char array) */
const char SCHOOL_NAME[] = "Embedded Systems Institute";

Variable vs Constant

PropertyVariableConstant
Can be changed?✓ Yes✗ No
Declared withint x;const int x;
StorageRegular RAMOften in read-only memory (ROM)
Use caseData that changes during executionFixed values like PI, MAX_SIZE
Reassignable?✓ Yes✗ Compiler error
24Best Practices

Good Coding Practices

Writing code that works is the minimum. Writing code that is readable, maintainable, and reliable is the professional standard. These practices apply from your first program onwards:

✓ Use Meaningful Names

✗ Bad
int a; float b; char x;
✓ Good
int studentAge; float examScore; char letterGrade;

✓ Always Initialize Variables

✗ Bad (undefined value)
int age; /* contains garbage */ float score; /* could be anything */
✓ Good (defined value)
int age = 0; float score = 0.0f;

✓ Keep Naming Consistent

✗ Bad (inconsistent style)
int A; float Age1; char student_grade; double S;
✓ Good (consistent camelCase)
int studentAge; float examScore; char studentGrade; double totalSalary;

✓ Write Comments That Explain Intent

✗ Bad (states the obvious)
x = x + 1; // Increment x
✓ Good (explains why)
// Retry after communication timeout retryCount++;
25Best Practices

Common Beginner Mistakes

⚠️
Learn From These First
These are the mistakes almost every beginner makes. Knowing them in advance will save you hours of debugging.

Mistake 1: Using Keywords as Variable Names

✗ Error
int return; /* "return" is a keyword */ int while = 5; /* "while" is a keyword */
✓ Correct
int result = 0; int count = 5;

Mistake 2: Starting Identifiers with Numbers

✗ Error
int 123marks; float 1stResult;
✓ Correct
int marks123; float firstResult;

Mistake 3: Spaces in Identifiers

✗ Error
int student marks; float total salary;
✓ Correct
int studentMarks; float totalSalary;

Mistake 4: Using Confusing Single-Letter Names

✗ Bad (unreadable)
int abc; float x1; char y;
✓ Better (self-documenting)
int totalMarks; float examPercentage; char gradeCategory;
26Best Practices

Memory Tricks & Mnemonics

Remember the Six Token Types

Use the mnemonic “Kind Intelligent Cats Sing Opera Softly” to remember all six token types:

K I C S O S
KKeywords
IIdentifiers
CConstants
SStrings
OOperators
SSymbols
“Kind Intelligent Cats Sing Opera Softly”

Remember Identifier Rules

Ask these four questions before naming an identifier — if you answer YES to all of them, the name is valid:

QuestionMust BeExample
Contains only letters, digits, underscore?YESstudent_1
Does it start with a letter or underscore?YESage, _count
No spaces anywhere?YESstudentAge
Is it NOT a keyword?YEScount (not while) ✅

Remember C Program Structure

Comments → Headers → Definitions → Globals → main() → Functions

Each section appears in this order, from top to bottom of the file

27Review

Interview Questions

These questions frequently appear in entrance tests, university exams, and technical interviews for embedded systems and systems programming roles.

Q1
What is a token?
A token is the smallest meaningful unit in a C program that the compiler recognizes. C has six types: Keywords, Identifiers, Constants, Strings, Operators, and Special Symbols. For example, in int age = 20;, each of int, age, =, 20, and ; is a separate token.
Q2
Can a keyword be used as an identifier?
No. Keywords are reserved words with predefined meaning in C. Using them as identifiers causes a compiler error. Example: int while = 5; is invalid because while is a keyword.
Q3
What is the difference between declaration and initialization?
  • Declaration creates the variable and reserves memory: int age;
  • Initialization assigns an initial value: age = 20;
  • Both can be done together: int age = 20;
Q4
Why should variables have meaningful names?
Meaningful names improve code readability, reduce programming errors, make debugging easier, and help other programmers (and your future self) understand the code without needing extensive comments. A name like totalMarks is instantly understandable; a name like t or x is not.
Q5
Is C case-sensitive?
Yes. C is fully case-sensitive. The compiler treats marks, Marks, and MARKS as three completely different identifiers. This is also why printf must be all lowercase — writing Printf or PRINTF will cause a compiler error.
Q6
What is the purpose of #include in a C program?
The #include directive tells the preprocessor to include the contents of a header file in your source code. This makes functions like printf() and scanf() available. Without #include <stdio.h>, the compiler would not recognize standard I/O functions.
Q7
Why is C called a middle-level language?
C is called a middle-level language because it bridges the gap between:
  • High-level languages (like Python, Java) — C supports functions, loops, if/else, and formatted I/O.
  • Low-level languages (like Assembly) — C supports direct memory access via pointers, bit manipulation, and hardware register access.
This dual nature makes C uniquely suited for systems programming and embedded development.
Q8
What does return 0; mean in main()?
By convention, return 0; in main() signals to the operating system that the program completed successfully. Any non-zero return value indicates an error. Many shell scripts and build systems check this return code to determine if a program ran correctly.
28Review

Practice Questions

🟢 Easy
  • Define a token in C. Give one example of each of the six types.
  • What is a keyword? List five C keywords and their purpose.
  • What is an identifier? What are the five rules for naming one?
  • What is a variable? How do you declare and initialize one?
  • What is a constant? How is it different from a variable?
  • What is the purpose of #include <stdio.h>?
  • Write a C program that displays the message "I am learning C".
🟠 Medium
  • Differentiate between variables and constants with code examples.
  • Explain all five rules for naming identifiers with valid and invalid examples.
  • Explain the difference between declaration and initialization. Show three ways to initialize a variable.
  • List the different types of tokens with one example of each.
  • What is the compilation process? Describe each of the four stages.
  • Explain the six structural sections of a C program with an annotated example.
🔨 Programming Exercises
  • Declare variables for: Student Name (string), Student Age (int), Student Marks (float). Initialize them with sample values and print them using printf().
  • Write a program that asks the user to enter their name and age, then prints a greeting: "Hello [Name], you are [Age] years old."
  • Declare one variable of each type: int, float, char, double. Initialize all four with appropriate values and print each with the correct format specifier.
  • Write a program that defines constants for PI (3.14159) and MAX_STUDENTS (50). Print both values with descriptive labels. Try assigning a new value to PI and observe the compiler error.
29Review

Chapter Summary

✓ Chapter 1 Completion Checklist
  • C is a general-purpose, procedural, compiled programming language created by Dennis Ritchie at Bell Labs in 1972
  • C was created to rewrite the UNIX operating system in a portable, efficient language superior to Assembly
  • The language has evolved through BCPL (1966) → B (1969) → C (1972) and continues to be standardized (C23)
  • C’s key features: simple, fast, portable, structured, modular, middle-level, and memory-efficient
  • C is used in operating systems, embedded systems, device drivers, compilers, databases, and networking
  • The compilation pipeline has four stages: Preprocessor → Compiler → Assembler → Linker
  • A C program has six structural sections: Documentation, Link, Definition, Global, main(), Functions
  • printf() displays output; scanf() reads input; both use format specifiers (%d, %f, %c, %s)
  • C has six token types: Keywords, Identifiers, Constants, Strings, Operators, Special Symbols (KICSОС)
  • Identifier rules: letters/digits/underscore only; no leading digit; no spaces; not a keyword; case-sensitive
  • Variables store changeable data; constants store fixed values declared with const
  • C = Power + Responsibility — great control over hardware requires careful, intentional programming
30Review

What’s Next?

You have completed Chapter 1 and built a solid foundation. Chapter 2 dives into the heart of C programming — the data model that makes the language so expressive and powerful in embedded systems:

📚 Chapter 2 — Data Types, Variables & Operators
Building on your Chapter 1 foundation with the complete C type system
Data Types & Memory Sizes
Type Modifiers (short, long, unsigned)
Variables in Depth
Literals & Numeric Systems
Type Conversion
Type Casting
All Arithmetic Operators
Relational & Logical Operators
Bitwise Operators
Operator Precedence & Associativity
Expressions & Evaluation Rules
Practice Programs & Interview Questions