C Language Cheat Sheet
Category |
Concept |
Description |
Example |
Basics |
Hello World |
Basic program to print "Hello, World!" |
c #include <stdio.h>
int main() { printf("Hello, World!\\n"); return 0; } |
Data Types |
Fundamental types: int, float, double, char, etc. |
c int a = 10; float b = 5.5; char c = 'A'; |
|
Variables |
Storage locations with type and name |
c int age = 25; float salary = 50000.0; |
|
Operators |
Arithmetic, Relational, Logical, Bitwise, Assignment operators |
c int sum = a + b; if (a > b && b < c) { /*...*/ } |
|
Control Flow |
If-Else |
Conditional branching |
c if (score >= 50) { printf("Pass"); } else { printf("Fail"); } |
Switch |
Multi-way branch based on variable value |
c switch (choice) { case 1: printf("One"); break; case 2: printf("Two"); break; default: printf("Other"); } |
|
Loops |
for, while, do-while for iteration |
c for(int i=0; i<10; i++) { printf("%d ", i); } |
|
Functions |
Function Declaration |
Define reusable code blocks with parameters and return types |
c int add(int x, int y); int add(int x, int y) { return x + y; } |
Recursion |
Function calling itself |
c int factorial(int n) { if (n <= 1) return 1; else return n * factorial(n - 1); } |
|
Arrays & Strings |
Arrays |
Collection of elements of the same type |
c int numbers[5] = {1, 2, 3, 4, 5}; |
Strings |
Array of characters terminated by null character \0 |
c char name[] = "Alice"; printf("Name: %s", name); |
|
Pointers |
Pointer Basics |
Variables that store memory addresses |
c int a = 10; int *ptr = &a; printf("%d", *ptr); // Outputs 10 |
Pointer Arithmetic |
Performing operations on pointers |
c ptr++; // Moves to next integer location |
|
Pointers to Pointers |
Pointers that store addresses of other pointers |
c int **pptr = &ptr; |
|
Structures |
Structs |
User-defined data types grouping different types |
c struct Person { char name[50]; int age; }; struct Person p1; p1.age = 30; |
Unions |
Similar to structs but share the same memory location |
c union Data { int i; float f; char str[20]; }; union Data data; data.i = 10; |
|
Memory Management |
Dynamic Memory Allocation |
Using malloc, calloc, realloc, and free to manage memory dynamically |
c int *arr = malloc(5 * sizeof(int)); if(arr != NULL) { /* use array */ free(arr); } |
File I/O |
File Operations |
Reading from and writing to files using fopen, fclose, fread, fwrite |
c FILE *fp = fopen("file.txt", "r"); if (fp) { char buffer[100]; fgets(buffer, 100, fp); fclose(fp); } |
Advanced |
Bit Manipulation |
Operations on individual bits using &, ` |
, ^, ~, <<, >>` |
Preprocessor Directives |
Compile-time instructions using #define, #include, #ifdef, etc. |
c #define PI 3.14 #include <stdio.h> |
|
Macros |
Define code snippets that are expanded by the preprocessor |
c #define SQUARE(x) ((x) * (x)) int sq = SQUARE(5); |
|
Enumerations |
Define named integer constants |
c enum Color { RED, GREEN, BLUE }; enum Color c = GREEN; |
|
Typedef |
Create alias for data types |
c typedef unsigned long ulong; ulong num = 1000; |
|
Standard Library |
Common Functions |
Utilize functions from standard libraries like math.h, string.h |
c #include <math.h> double result = sqrt(25.0); #include <string.h> int len = strlen("Hello"); |
Concurrency |
Threads (POSIX) |
Creating and managing threads using POSIX pthread library |
c #include <pthread.h> void *print_message(void *ptr) { printf("%s", (char*)ptr); return NULL; } pthread_t thread; pthread_create(&thread, NULL, print_message, "Hello"); pthread_join(thread, NULL); |
Networking |
Sockets |
Basic socket programming for network communication |
c #include <sys/socket.h> // Create socket int sock = socket(AF_INET, SOCK_STREAM, 0); |
Optimization |
Inline Functions |
Suggest compiler to inline functions for performance |
c inline int max(int a, int b) { return (a > b) ? a : b; } |
Compiler Flags |
Use flags like -O2, -Wall for optimization and warnings |
bash gcc -O2 -Wall program.c -o program |
|
Debugging |
Using gdb |
Debugging programs with GNU Debugger |
bash gcc -g program.c -o program gdb ./program |
Best Practices |
Code Modularity |
Write modular code using functions and separate files |
Organize code into .c and .h files |
Commenting |
Use comments to explain code logic |
c // This function adds two numbers int add(int a, int b) { return a + b; } |
|
Advanced Topics |
Function Pointers |
Pointers that reference functions for callbacks and dynamic behavior |
c int add(int a, int b) { return a + b; } int (*func_ptr)(int, int) = &add; int result = func_ptr(2, 3); |
Dynamic Libraries |
Create and use shared libraries (.so files) |
Compile with gcc -shared -o libmylib.so -fPIC mylib.c and link with -lmylib |
|
Memory Alignment |
Align data structures in memory for performance |
c struct __attribute__((aligned(16))) AlignedStruct { int a; double b; }; |
|
Concurrency Control |
Use mutexes and semaphores to manage concurrent access |
c #include <pthread.h> pthread_mutex_t lock; pthread_mutex_lock(&lock); // critical section pthread_mutex_unlock(&lock); |
|
Advanced Pointer Usage |
Dangling pointers, wild pointers, pointer arithmetic complexities |
Ensure pointers are initialized and managed properly to avoid undefined behavior |
|
Error Handling |
Return Codes |
Use return values to indicate success or failure |
c int readFile(const char *filename) { FILE *fp = fopen(filename, "r"); if (!fp) return -1; // ... return 0; } |
errno and perror |
Standard error reporting mechanisms |
c #include <errno.h> #include <stdio.h> if (fopen("nonexistent.txt", "r") == NULL) { perror("Error opening file"); } |
|
Miscellaneous |
Enum and Bitfields |
Use enums for readable constants and bitfields for memory-efficient flags |
c struct Flags { unsigned int flag1 : 1; unsigned int flag2 : 1; }; |
Inline Assembly |
Embed assembly code within C for low-level operations |
c int a, b; asm ("addl %%ebx, %%eax;" : "=a" (a) : "a" (a), "b" (b)); |
|
Templates/Generics |
Generic Programming |
Use macros or void* to achieve generic-like functionality in C |
c #define MAX(a,b) ((a) > (b) ? (a) : (b)) int max = MAX(5, 10); |
Comments
Post a Comment