diff --git a/c-cheatsheet.md b/c-cheatsheet.md new file mode 100644 index 0000000..e7d433d --- /dev/null +++ b/c-cheatsheet.md @@ -0,0 +1,590 @@ +# C Programming Language Cheatsheet + +## Program Structure + +```c +#include // Include standard I/O library + +// Function prototype declaration +void myFunction(int param); + +// Global variables +int globalVar = 10; + +// Main function - program entry point +int main() { + // Code statements + printf("Hello, World!\n"); + + return 0; // Return value to OS (0 = success) +} + +// Function definition +void myFunction(int param) { + // Function body +} +``` + +## Data Types + +| Type | Description | Format Specifier | Example | +|------|-------------|------------------|---------| +| `int` | Integer | `%d` or `%i` | `int x = 10;` | +| `float` | Single-precision floating point | `%f` | `float y = 10.5f;` | +| `double` | Double-precision floating point | `%lf` | `double z = 10.5;` | +| `char` | Single character | `%c` | `char c = 'A';` | +| `char[]` | String (character array) | `%s` | `char str[] = "hello";` | +| `short` | Short integer | `%hd` | `short s = 10;` | +| `long` | Long integer | `%ld` | `long l = 10L;` | +| `long long` | Long long integer | `%lld` | `long long ll = 10LL;` | +| `unsigned int` | Unsigned integer | `%u` | `unsigned int ui = 10u;` | +| `unsigned char` | Unsigned character | `%c` | `unsigned char uc = 255;` | +| `size_t` | Size type (for sizes) | `%zu` | `size_t size = sizeof(int);` | + +## Variable Declaration + +```c +// Basic declaration +int a; // Declaration +int b = 10; // Declaration with initialization +const int MAX = 100; // Constant (cannot be modified) + +// Multiple variables +int x, y, z; +int p = 1, q = 2, r = 3; + +// Type modifiers +unsigned int positive; // Only non-negative values +signed int withSign; // Can be positive or negative +long int bigNumber; // Larger range of values +short int smallNumber; // Smaller range of values +``` + +## Operators + +### Arithmetic Operators + +| Operator | Description | Example | Result | +|----------|-------------|---------|--------| +| `+` | Addition | `a + b` | `13` | +| `-` | Subtraction | `a - b` | `7` | +| `*` | Multiplication | `a * b` | `30` | +| `/` | Division | `a / b` | `3` (integer division) | +| `%` | Modulus (remainder) | `a % b` | `1` | +| `-` | Negation | `-a` | `-10` | +| `++` | Increment | `a++` | `a` becomes `11` | +| `--` | Decrement | `b--` | `b` becomes `2` | + +### Comparison Operators + +| Operator | Description | Example | +|----------|-------------|---------| +| `==` | Equal to | `a == b` | +| `!=` | Not equal to | `a != b` | +| `>` | Greater than | `a > b` | +| `<` | Less than | `a < b` | +| `>=` | Greater than or equal to | `a >= b` | +| `<=` | Less than or equal to | `a <= b` | + +### Logical Operators + +| Operator | Description | Example | +|----------|-------------|---------| +| `&&` | Logical AND | `a && b` | +| `\|\|` | Logical OR | `a \|\| b` | +| `!` | Logical NOT | `!a` | + +### Bitwise Operators + +| Operator | Description | Example | Notes | +|----------|-------------|---------|-------| +| `&` | Bitwise AND | `a & b` | | +| `\|` | Bitwise OR | `a \| b` | | +| `^` | Bitwise XOR | `a ^ b` | | +| `~` | Bitwise NOT | `~a` | | +| `<<` | Left shift | `a << 2` | Multiply by 2² | +| `>>` | Right shift | `a >> 2` | Divide by 2² | + +### Assignment Operators + +| Operator | Description | Equivalent | +|----------|-------------|------------| +| `=` | Simple assignment | `a = b` | +| `+=` | Add and assign | `a = a + b` | +| `-=` | Subtract and assign | `a = a - b` | +| `*=` | Multiply and assign | `a = a * b` | +| `/=` | Divide and assign | `a = a / b` | +| `%=` | Modulus and assign | `a = a % b` | +| `&=` | Bitwise AND and assign | `a = a & b` | +| `\|=` | Bitwise OR and assign | `a = a \| b` | +| `^=` | Bitwise XOR and assign | `a = a ^ b` | +| `<<=` | Left shift and assign | `a = a << b` | +| `>>=` | Right shift and assign | `a = a >> b` | + +## Control Structures + +### Conditional Statements + +| Statement | Syntax | Description | +|-----------|--------|-------------| +| If | `if (condition) { statements }` | Executes statements if condition is true | +| If-else | `if (condition) { statements1 } else { statements2 }` | Executes statements1 if condition is true, otherwise statements2 | +| If-else if-else | `if (condition1) { statementsA } else if (condition2) { statementsB } else { statementsC }` | Tests multiple conditions in sequence | +| Ternary operator | `result = (condition) ? valueIfTrue : valueIfFalse;` | Shorthand for simple if-else assignment | +| Switch | `switch (expression) { case value1: statements1; break; case value2: statements2; break; default: statementsDefault; }` | Multi-way branch based on expression value | + +### Switch Statement Example + +```c +switch (grade) { + case 'A': + printf("Excellent!\n"); + break; + case 'B': + printf("Good job!\n"); + break; + case 'C': + printf("Average performance.\n"); + break; + default: + printf("Need improvement.\n"); +} +``` + +### Loops + +| Loop Type | Syntax | Description | +|-----------|--------|-------------| +| For | `for (initialization; condition; update) { statements }` | Repeats statements while condition is true, with initialization before first iteration and update after each iteration | +| While | `while (condition) { statements }` | Repeats statements while condition is true | +| Do-while | `do { statements } while (condition);` | Executes statements at least once, then repeats while condition is true | + +### Loop Control + +| Statement | Description | +|-----------|-------------| +| `break;` | Exits the innermost loop or switch | +| `continue;` | Skips to the next iteration of the loop | + +## Arrays + +```c +// Declaration and initialization +int numbers[5]; // Uninitialized array of 5 integers +int scores[5] = {90, 85, 88, 92, 76}; // Initialized array +int partial[5] = {90, 85}; // Remaining elements initialized to 0 +int auto_size[] = {1, 2, 3}; // Size determined automatically (3) + +// Accessing elements (0-indexed) +int first = scores[0]; // 90 +scores[4] = 95; // Modify element + +// Multidimensional arrays +int matrix[3][4]; // 3×4 matrix (3 rows, 4 columns) +int grid[2][3] = { + {1, 2, 3}, + {4, 5, 6} +}; +int value = grid[1][0]; // 4 (row 1, column 0) +``` + +## Strings + +```c +// String declaration and initialization +char greeting[] = "Hello"; // Includes null terminator '\0' automatically +char name[10] = "John"; // Array size should be at least string length + 1 +char empty[10] = ""; // Empty string + +// Accessing characters +char first = name[0]; // 'J' +name[0] = 'j'; // Modify character + +// Common string functions (include ) +strlen(str); // String length (excludes null terminator) +strcpy(dest, src); // Copy string src to dest +strcat(dest, src); // Concatenate src to the end of dest +strcmp(s1, s2); // Compare strings (0 if equal, <0 if s10 if s1>s2) +strchr(str, ch); // Find first occurrence of character ch in str +strstr(str, sub); // Find first occurrence of substring sub in str +``` + +## Pointers + +```c +// Declaration and initialization +int x = 10; +int *ptr = &x; // ptr contains the memory address of x + +// Dereferencing (accessing the value at the address) +int value = *ptr; // value = 10 + +// Pointer arithmetic +int arr[5] = {10, 20, 30, 40, 50}; +int *p = arr; // p points to the first element of arr +int second = *(p + 1); // 20 (second element) + +// Null pointer +int *nullPtr = NULL; // Points to nothing (always check before dereferencing) + +// Pointers and arrays +int arr[5] = {10, 20, 30, 40, 50}; +int *ptr = arr; // Points to first element +// These are equivalent: +int val1 = arr[2]; +int val2 = *(arr + 2); +int val3 = ptr[2]; +int val4 = *(ptr + 2); +``` + +## Functions + +### Function Syntax + +| Component | Syntax | Description | +|-----------|--------|-------------| +| Declaration | `return_type function_name(parameter_type param1, ...);` | Function prototype (declares the function) | +| Definition | `return_type function_name(parameter_type param1, ...) { statements }` | Actual function code | +| Call | `function_name(argument1, argument2, ...);` | Invoking the function | +| Return | `return value;` | Exit function and return a value (if not void) | + +### Function Types and Examples + +| Function Type | Example | Description | +|---------------|---------|-------------| +| With return value | `int add(int a, int b) { return a + b; }` | Returns calculated result | +| Without return value | `void printMessage(const char *msg) { printf("%s\n", msg); }` | Performs action, returns nothing | +| Pass by value | `void increment(int x) { x++; }` | Changes only affect local copy | +| Pass by reference | `void increment(int *x) { (*x)++; }` | Changes affect original variable | +| Recursive | `int factorial(int n) { if (n <= 1) return 1; return n * factorial(n-1); }` | Function calls itself | + +### Parameter Passing + +| Method | Example Call | Effect on Original | +|--------|--------------|-------------------| +| By value | `increment(num);` | No change to original | +| By reference | `increment(&num);` | Original can be modified | +| Array | `process(array);` | Original array can be modified | +| Const reference | `display(const int *arr, int size);` | Prevents modification of original | + +```c +// Example of function usage +int num = 5; +incrementByValue(num); // num remains 5 +incrementByReference(&num); // num becomes 6 +``` + +## Structures + +```c +// Structure definition +struct Person { + char name[50]; + int age; + float height; +}; + +// Declaration and initialization +struct Person person1; +struct Person person2 = {"John", 25, 1.75}; + +// Accessing members +strcpy(person1.name, "Jane"); +person1.age = 22; +person1.height = 1.65; + +// Structure pointer +struct Person *ptr = &person1; +printf("%s\n", ptr->name); // Arrow operator for pointer access +// Equivalent to: printf("%s\n", (*ptr).name); + +// Typedef for simpler naming +typedef struct { + char title[100]; + char author[50]; + int year; +} Book; + +Book novel = {"The Great Gatsby", "F. Scott Fitzgerald", 1925}; +``` + +## Memory Management + +```c +// Dynamic memory allocation (include ) +int *ptr = malloc(5 * sizeof(int)); // Allocate memory for 5 integers +if (ptr == NULL) { + // Allocation failed +} + +// Initialize allocated memory +memset(ptr, 0, 5 * sizeof(int)); // Set all bytes to 0 (include ) + +// Reallocation +ptr = realloc(ptr, 10 * sizeof(int)); // Resize to 10 integers + +// Free allocated memory (prevent memory leaks) +free(ptr); +ptr = NULL; // Good practice to avoid dangling pointers +``` + +## File I/O + +### File Operations + +| Operation | Function | Description | +|-----------|----------|-------------| +| Open | `FILE *file = fopen(filename, mode);` | Open a file with specified mode | +| Close | `fclose(file);` | Close a file and flush buffers | +| Check EOF | `feof(file)` | Check if end-of-file is reached | +| Get error | `ferror(file)` | Check if an error occurred | +| Flush | `fflush(file)` | Flush output buffer | +| Reposition | `fseek(file, offset, origin)` | Move file position indicator | +| Get position | `ftell(file)` | Get current file position | +| Rewind | `rewind(file)` | Set position to beginning of file | + +### File Open Modes + +| Mode | Description | +|------|-------------| +| `"r"` | Read (file must exist) | +| `"w"` | Write (create new or truncate existing) | +| `"a"` | Append (create new or append to existing) | +| `"r+"` | Read and write (file must exist) | +| `"w+"` | Read and write (create new or truncate existing) | +| `"a+"` | Read and append (create new or append to existing) | +| `"b"` | Binary mode (add to modes above, e.g., `"rb"`, `"wb"`) | + +### Text File I/O + +| Operation | Function | Description | +|-----------|----------|-------------| +| Read formatted | `fscanf(file, format, ...)` | Read formatted data | +| Write formatted | `fprintf(file, format, ...)` | Write formatted data | +| Read line | `fgets(buffer, size, file)` | Read a line of text | +| Write string | `fputs(string, file)` | Write a string | +| Read character | `fgetc(file)` or `getc(file)` | Read a character | +| Write character | `fputc(c, file)` or `putc(c, file)` | Write a character | + +### Binary File I/O + +| Operation | Function | Description | +|-----------|----------|-------------| +| Read | `fread(buffer, size, count, file)` | Read binary data | +| Write | `fwrite(buffer, size, count, file)` | Write binary data | + +### Example + +```c +// Writing to a text file +FILE *file = fopen("data.txt", "w"); +if (file == NULL) { + perror("Error opening file"); + return 1; +} +fprintf(file, "Name: %s, Age: %d\n", "John", 25); +fclose(file); + +// Reading from a text file +char name[50]; +int age; +file = fopen("data.txt", "r"); +if (file != NULL) { + fscanf(file, "Name: %s, Age: %d", name, &age); + fclose(file); +} +``` + +## Preprocessor Directives + +### Basic Preprocessor Directives + +| Directive | Syntax | Description | +|-----------|--------|-------------| +| Include | `#include ` | Include system header file | +| Include | `#include "filename"` | Include local header file | +| Define | `#define NAME value` | Define a macro constant | +| Define function | `#define NAME(params) expression` | Define a function-like macro | +| Undefine | `#undef NAME` | Remove a macro definition | +| Error | `#error message` | Force compilation error with message | +| Pragma | `#pragma token` | Implementation-specific instructions | + +### Conditional Compilation + +| Directive | Syntax | Description | +|-----------|--------|-------------| +| If defined | `#ifdef SYMBOL` | True if SYMBOL is defined | +| If not defined | `#ifndef SYMBOL` | True if SYMBOL is not defined | +| If expression | `#if EXPRESSION` | True if EXPRESSION is non-zero | +| Else if | `#elif EXPRESSION` | Alternative condition | +| Else | `#else` | Default condition | +| End if | `#endif` | End conditional block | + +### Predefined Macros + +| Macro | Description | +|-------|-------------| +| `__FILE__` | Current source filename (string) | +| `__LINE__` | Current line number (integer) | +| `__DATE__` | Compilation date (string) | +| `__TIME__` | Compilation time (string) | +| `__STDC__` | 1 if compiler conforms to ANSI C | +| `__cplusplus` | Defined when compiled with C++ compiler | +| `__func__` | Current function name (string) | + +### Macro Examples + +```c +// Simple constant macro +#define PI 3.14159 + +// Function-like macro with arguments +#define SQUARE(x) ((x) * (x)) +#define MAX(a, b) ((a) > (b) ? (a) : (b)) + +// Stringification operator (#) +#define STRINGIFY(x) #x +// Usage: STRINGIFY(hello) becomes "hello" + +// Token concatenation operator (##) +#define CONCAT(a, b) a##b +// Usage: CONCAT(num, 123) becomes num123 +``` + +## Error Handling + +```c +// Error handling with return values +if (function() == -1) { + // Handle error +} + +// Using errno (include ) +#include +if (func() == -1) { + printf("Error: %d\n", errno); + perror("Error message"); // Print error message based on errno +} + +// Exit program (include ) +exit(EXIT_SUCCESS); // Normal termination +exit(EXIT_FAILURE); // Error termination +``` + +## Command Line Arguments + +```c +int main(int argc, char *argv[]) { + // argc: Number of arguments (including program name) + // argv: Array of argument strings + + printf("Program name: %s\n", argv[0]); + + for (int i = 1; i < argc; i++) { + printf("Argument %d: %s\n", i, argv[i]); + } + + return 0; +} +``` + +## Common Library Functions + +### Standard I/O (stdio.h) + +| Function | Syntax | Description | +|----------|--------|-------------| +| `printf` | `printf("Format", args...);` | Formatted output to stdout | +| `scanf` | `scanf("%d", &variable);` | Formatted input from stdin | +| `puts` | `puts("string");` | Output string with newline | +| `gets` | `gets(string);` | Input string (unsafe, avoid using) | +| `putchar` | `putchar('c');` | Output character | +| `getchar` | `getchar();` | Input character | +| `fprintf` | `fprintf(file, "Format", args);` | Formatted output to file | +| `fscanf` | `fscanf(file, "%d", &var);` | Formatted input from file | +| `fgets` | `fgets(str, size, file);` | Input line from file (safe) | +| `sprintf` | `sprintf(str, "Format", args);` | Formatted output to string | + +### String Handling (string.h) + +| Function | Syntax | Description | +|----------|--------|-------------| +| `strlen` | `strlen(str);` | String length | +| `strcpy` | `strcpy(dest, src);` | String copy | +| `strncpy` | `strncpy(dest, src, n);` | Copy up to n characters | +| `strcat` | `strcat(dest, src);` | String concatenation | +| `strncat` | `strncat(dest, src, n);` | Concatenate up to n characters | +| `strcmp` | `strcmp(s1, s2);` | String comparison | +| `strncmp` | `strncmp(s1, s2, n);` | Compare up to n characters | +| `strchr` | `strchr(str, c);` | Find character in string | +| `strstr` | `strstr(str, substr);` | Find substring in string | +| `strtok` | `strtok(str, delim);` | Tokenize string | + +### Memory Functions (string.h) + +| Function | Syntax | Description | +|----------|--------|-------------| +| `memcpy` | `memcpy(dest, src, n);` | Memory copy | +| `memmove` | `memmove(dest, src, n);` | Safe memory copy (handles overlap) | +| `memset` | `memset(ptr, value, n);` | Fill memory with value | +| `memcmp` | `memcmp(ptr1, ptr2, n);` | Compare memory blocks | + +### Math Functions (math.h) + +| Function | Syntax | Description | +|----------|--------|-------------| +| `sqrt` | `sqrt(x);` | Square root | +| `pow` | `pow(x, y);` | x raised to power y | +| `ceil` | `ceil(x);` | Round up to integer | +| `floor` | `floor(x);` | Round down to integer | +| `round` | `round(x);` | Round to nearest integer | +| `fabs` | `fabs(x);` | Absolute value (float) | +| `sin`, `cos`, `tan` | `sin(x);` | Trigonometric functions | +| `asin`, `acos`, `atan` | `asin(x);` | Inverse trigonometric functions | +| `log`, `log10` | `log(x);` | Natural and base-10 logarithms | +| `exp` | `exp(x);` | e raised to power x | + +### Character Functions (ctype.h) + +| Function | Syntax | Returns true if character is... | +|----------|--------|--------------------------------| +| `isalpha` | `isalpha(c);` | Alphabetic (a-z, A-Z) | +| `isdigit` | `isdigit(c);` | Decimal digit (0-9) | +| `isalnum` | `isalnum(c);` | Alphanumeric (a-z, A-Z, 0-9) | +| `isspace` | `isspace(c);` | Whitespace (space, tab, newline, etc.) | +| `islower` | `islower(c);` | Lowercase (a-z) | +| `isupper` | `isupper(c);` | Uppercase (A-Z) | +| `tolower` | `tolower(c);` | Convert to lowercase | +| `toupper` | `toupper(c);` | Convert to uppercase | + +### Memory Management (stdlib.h) + +| Function | Syntax | Description | +|----------|--------|-------------| +| `malloc` | `malloc(size);` | Allocate memory | +| `calloc` | `calloc(n, size);` | Allocate and zero memory | +| `realloc` | `realloc(ptr, size);` | Resize memory allocation | +| `free` | `free(ptr);` | Free allocated memory | + +### Other Utility Functions (stdlib.h) + +| Function | Syntax | Description | +|----------|--------|-------------| +| `atoi` | `atoi(str);` | Convert string to int | +| `atof` | `atof(str);` | Convert string to double | +| `rand` | `rand();` | Generate random number | +| `srand` | `srand(seed);` | Seed random number generator | +| `qsort` | `qsort(arr, n, size, cmp);` | Sort array | +| `bsearch` | `bsearch(key, arr, n, size, cmp);` | Binary search | +| `exit` | `exit(status);` | Terminate program | +| `abs` | `abs(n);` | Integer absolute value | + +### Time Functions (time.h) + +| Function | Syntax | Description | +|----------|--------|-------------| +| `time` | `time(NULL);` | Current time (seconds since epoch) | +| `clock` | `clock();` | Processor time used | +| `difftime` | `difftime(time2, time1);` | Time difference in seconds | +| `localtime` | `localtime(&time_t);` | Convert to local time struct | +| `strftime` | `strftime(str, size, format, tm);` | Format time as string | \ No newline at end of file