2026-03-23
c language
My AI generated notes on C for re-learning purposes.
This guide covers all the core topics you’ll find on W3Schools’ C Tutorial but in a much shorter, “cheat‑sheet” style. Use it as a quick reference or a refresher before diving into projects.
1. Introduction
- What is C? A general‑purpose, procedural language created by Dennis Ritchie (1972). It’s the foundation for many modern languages and operating systems.
- Why learn C?
- Low‑level memory control → performance & embedded systems.
- Portable: compiles to almost every platform.
- Huge ecosystem of libraries.
2. Program Structure
#include <stdio.h> // Preprocessor directive – include header files
int main(void) { // Entry point
/* code */
return 0; // Exit status
} #includepulls in declarations from headers (<stdio.h>,<stdlib.h>, etc.).main()is mandatory.- Return
0signals success.
3. Syntax Basics
| Element | Example | Notes |
|---|---|---|
| Comments | /* block */ or // line | Used for documentation. |
| Identifiers | myVar, calculate_sum | Must start with letter/underscore, no spaces. |
| Semicolon | int x = 5; | Terminates statements. |
4. Variables & Data Types
| Type | Size (typical) | Range / Example |
|---|---|---|
char | 1 byte | 'A', '\n' |
int | 2–4 bytes | -2,147,483,648 … 2,147,483,647 (4-byte) |
short | 2 bytes | -32768 … 32767 |
long | 4–8 bytes | -9,223,372,036,854,775,808 … 9,223,372,036,854,775,807 (8-byte) |
float | 4 bytes | 3.14f |
double | 8 bytes | 3.1415926535 |
_Bool | 1 byte | true / false (C99) |
Tip: Use
sizeof(type)to discover exact size on your platform.
5. Operators
| Category | Symbols | Example |
|---|---|---|
| Arithmetic | + - * / % | a + b, c / d |
| Assignment | = += -= *= /= %= | x = y; x += 2; |
| Comparison | == != < > <= >= | if (a == b) |
| Logical | && || ! | if (!flag && count) |
| Bitwise | & | ^ ~ << >> | mask & 0xFF |
| Increment/Decrement | ++ -- | i++; --j; |
Operator precedence follows the standard C rules (see reference table if needed).
6. Booleans
- Use
_Boolorint(0 = false, non‑zero = true). - Standard header
<stdbool.h>definesbool,true,false.
#include <stdbool.h>
bool ok = true; 7. Conditional Statements
if / else if / else
if (score >= 90) printf("A");
else if (score >= 80) printf("B");
else printf("C"); - Ternary operator:
char grade = (score >= 60) ? 'P' : 'F';
switch
switch(day) {
case MONDAY: /* code */ break;
case TUESDAY: /* code */ break;
default: /* code */
} - Use
breakto exit the switch; omit for fall‑through.
8. Loops
| Loop | Syntax | When to use |
|---|---|---|
| while | while (cond) { … } | Condition checked before each iteration. |
| do‑while | do { … } while(cond); | At least one execution; condition after loop. |
| for | for(init; cond; incr) { … } | Classic counter loops. |
// Print 1–10
for (int i = 1; i <= 10; ++i)
printf("%d ", i); - break – exit loop immediately.
- continue – skip to next iteration.
9. Arrays
int nums[5] = {1, 2, 3, 4, 5};
printf("%d", nums[0]); // Access by index (0‑based) - Multidimensional:
int matrix[3][4]; - Size can be inferred:
int a[] = {1,2,3};→ size 3.
10. Strings
- In C, strings are arrays of
charterminated by'\0'. - Use
<string.h>functions:
#include <string.h>
char s[20];
strcpy(s, "Hello");
printf("%s", s); // prints Hello Common functions: strlen, strcmp, strcat (from <string.h>); sprintf (from <stdio.h>).
11. User Input
int age;
scanf("%d", &age); // Note the address-of operator (&) - Always check return value of
scanffor errors.
12. Pointers
int x = 10;
int *p = &x; // p holds address of x
printf("%d", *p); // dereference → 10 - Pointer arithmetic:
p++moves to next element in array type. - Pointers to arrays:
int arr[5]; int *q = arr;(same as &arr[0]). - Null pointer:
NULL(macro from<stddef.h>).
13. Functions
Declaration / Prototype
int add(int a, int b); // prototype Definition
int add(int a, int b) {
return a + b;
} - Parameters are passed by value (copy).
- Return type can be
voidif nothing is returned.
Scope & Lifetime
| Scope | Example |
|---|---|
| Local | Inside function – destroyed on exit. |
| Global | Outside all functions – visible everywhere. |
14. Recursion
int fact(int n) {
return (n <= 1) ? 1 : n * fact(n-1);
} - Base case prevents infinite recursion.
15. Function Pointers
int (*func_ptr)(int, int) = add; // points to add()
int result = func_ptr(3, 4); // calls add(3,4) Useful for callbacks and generic algorithms.
16. File I/O
| Mode | Symbol |
|---|---|
"r" | read (text) |
"w" | write (truncate) |
"a" | append |
"rb/wb/ab" | binary |
FILE *fp = fopen("data.txt", "r");
if (!fp) { perror("fopen"); exit(1); }
char line[256];
while (fgets(line, sizeof line, fp))
printf("%s", line);
fclose(fp); - Use
<stdio.h>functions:fprintf,fscanf,fwrite,fread.
17. Structures & Unions
struct Person {
char name[50];
int age;
};
struct Person p = {"Alice", 30}; - Unions share memory among members; only one active at a time.
union Data { int i; float f; }; 18. Enumerations
enum Color { RED, GREEN, BLUE };
enum Color c = GREEN; - Underlying type is
intby default.
19. Memory Management
| Function | Purpose |
|---|---|
malloc(size) | Allocate raw memory |
calloc(n, size) | Allocate & zero-initialize |
realloc(ptr, newsize) | Resize block |
free(ptr) | Release memory |
int *arr = malloc(10 * sizeof(int));
if (!arr) { /* handle error */ }
...
free(arr); - Memory leaks: forgetting to free.
- Dangling pointers: using after free.
20. Errors & Debugging
| Technique | Description |
|---|---|
perror() | Print last system error |
assert(expr) | Abort if expression false (debug mode) |
#define DEBUG + conditional prints | |
| Valgrind / AddressSanitizer – detect leaks, invalid accesses |
21. Miscellaneous
- Macros (
#define) for constants or inline code. - Storage classes:
auto,register,static,extern. - Bitwise operations: useful for flags and low‑level data packing.
- Fixed‑width integers (
<stdint.h>):int32_t,uint64_t.
22. Quick Reference Cheat Sheet
/* Header includes */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
/* Main skeleton */
int main(void) {
/* code */
return 0;
}
/* Example: print Hello World */
printf("Hello, World!\n");
/* Example: read integer */
int n; scanf("%d", &n);
/* Example: array loop */
for (int i = 0; i < 5; ++i)
printf("%d ", arr[i]);
/* Example: function prototype */
int add(int a, int b); Final Note
This guide is intentionally terse. For deeper explanations, examples, and exercises, refer to the full W3Schools C tutorial or any comprehensive textbook (e.g., The C Programming Language by Kernighan & Ritchie). Happy coding!