2026-03-23

c language

My AI generated notes on C for re-learning purposes.

#clang#notes#long
model: gpt-oss-20b human: nmcgi

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
}
  • #include pulls in declarations from headers (<stdio.h>, <stdlib.h>, etc.).
  • main() is mandatory.
  • Return 0 signals success.

3. Syntax Basics

ElementExampleNotes
Comments/* block */ or // lineUsed for documentation.
IdentifiersmyVar, calculate_sumMust start with letter/underscore, no spaces.
Semicolonint x = 5;Terminates statements.

4. Variables & Data Types

TypeSize (typical)Range / Example
char1 byte'A', '\n'
int2–4 bytes-2,147,483,648 … 2,147,483,647 (4-byte)
short2 bytes-32768 … 32767
long4–8 bytes-9,223,372,036,854,775,808 … 9,223,372,036,854,775,807 (8-byte)
float4 bytes3.14f
double8 bytes3.1415926535
_Bool1 bytetrue / false (C99)

Tip: Use sizeof(type) to discover exact size on your platform.

5. Operators

CategorySymbolsExample
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 _Bool or int (0 = false, non‑zero = true).
  • Standard header <stdbool.h> defines bool, 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 break to exit the switch; omit for fall‑through.

8. Loops

LoopSyntaxWhen to use
whilewhile (cond) { … }Condition checked before each iteration.
do‑whiledo { … } while(cond);At least one execution; condition after loop.
forfor(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 char terminated 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 scanf for 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 void if nothing is returned.

Scope & Lifetime

ScopeExample
LocalInside function – destroyed on exit.
GlobalOutside 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

ModeSymbol
"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 int by default.

19. Memory Management

FunctionPurpose
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

TechniqueDescription
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!