C
BASIC STRUCTURE
#include <stdio.h>
int main() {
// code
return 0;
}
Data Types
| Type |
Size |
Format |
Range |
char |
1 byte |
%c |
-128 to 127 |
int |
4 bytes |
%d |
-2,147,483,648 to 2,147,483,647 |
float |
4 bytes |
%f |
3.4E-38 to 3.4E+38 |
double |
8 bytes |
%lf |
1.7E-308 to 1.7E+308 |
short |
2 bytes |
%hd |
-32,768 to 32,767 |
long |
8 bytes |
%ld |
-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
/* --- INPUT/OUTPUT CHEAT SHEET --- */
// Standard Console I/O
printf("Value: %d\n", num); // Output formatted data
scanf("%d", &num); // Input formatted data (use & for address)
getchar(); // Read a single character from stdin
putchar('A'); // Write a single character to stdout
puts("Hello"); // Print string + automatic newline
fgets(str, 100, stdin); // Read string safely (prevents overflow)
// String Buffer I/O (In-memory)
sprintf(buffer, "Age: %d", age); // Write formatted data TO a string
sscanf(buffer, "%d", &age); // Read formatted data FROM a string
// File Stream I/O
FILE *fp = fopen("data.txt", "r"); // Open for reading ("r"), writing ("w"), or appending ("a")
fprintf(fp, "ID: %d", id); // Print formatted data to file
fscanf(fp, "%d", &id); // Read formatted data from file
fputs("No newline", fp); // Write string to file without adding \n
fgetc(fp); // Read single character from file
fclose(fp); // Always close your file pointers!
// Essential Format Specifiers
// %d (int), %u (unsigned), %f (float), %lf (double), %c (char), %s (string), %p (pointer)
// Buffer Clearing Trick (Fixes skipped scanf/fgets issues)
while ((getchar()) != '\n' && getchar() != EOF);
| Specifier |
Type |
%d, %i |
Integer |
%f |
Float |
%lf |
Double |
%c |
Character |
%s |
String |
%p |
Pointer |
%x |
Hexadecimal |
%o |
Octal |
%% |
Print % |
Operators
// ARITHMETIC
+ - * / % ++ --
// RELATIONAL
== != > < >= <=
// LOGICAL
&& || !
// BITWISE
& | ^ ~ << >>
// ASSIGNMENT
= += -= *= /= %= &= |= ^= <<= >>=
// TERNARY
condition ? true : false
Control flow
// IF-ELSE
if (x > 0) { }
else if (x == 0) { }
else { }
// SWITCH
switch(x) {
case 1: break;
case 2: break;
default: break;
}
// FOR LOOP
for (int i = 0; i < 10; i++) { }
// WHILE LOOP
while (condition) { }
// DO-WHILE
do { } while (condition);
// BREAK, CONTINUE
break; // Exit loop
continue; // Skip iteration
Functions
// DECLARATION
return_type func_name(type param);
// DEFINITION
int add(int a, int b) {
return a + b;
}
// CALL
result = add(5, 3);
Arrays
int arr[5]; // Declaration
int arr[] = {1,2,3,4,5}; // Initialization
arr[0] = 10; // Access
int len = sizeof(arr)/sizeof(arr[0]); // Length
// 2D ARRAY
int matrix[3][3] = {{1,2,3}, {4,5,6}, {7,8,9}};
Strings
/* --- STRING MANIPULATION (<string.h>) --- */
char str[100] = "Hello";
strlen(str); // Returns length (excluding null terminator '\0')
strcpy(dest, src); // Copy src to dest (risky if dest is small)
strncpy(dest, src, n); // Copy up to n characters (safer)
strcat(dest, src); // Append src to end of dest
strncat(dest, src, n); // Append up to n characters (safer)
strcmp(s1, s2); // Compare: 0 if equal, <0 if s1 < s2, >0 if s1 > s2
strncmp(s1, s2, n); // Compare first n characters
strcasecmp(s1, s2); // Case-insensitive compare (POSIX/Strings.h)
// Searching & Tokenizing
strchr(str, 'c'); // Pointer to first occurrence of 'c' (NULL if not found)
strrchr(str, 'c'); // Pointer to LAST occurrence of 'c'
strstr(str, "sub"); // Pointer to first occurrence of substring "sub"
strspn(str, "abc"); // Length of initial segment containing only 'a', 'b', or 'c'
strcspn(str, "123"); // Length of initial segment NOT containing '1', '2', or '3'
strtok(str, ","); // Tokenize string by delimiter (updates state with NULL)
// Character Logic (<ctype.h>) - Useful for loops
isalpha(c); // Non-zero if alphabetic
isdigit(c); // Non-zero if 0-9
isspace(c); // Non-zero if whitespace (space, tab, \n)
toupper(c); // Convert to uppercase
tolower(c); // Convert to lowercase
// Memory Operations (also in <string.h>)
memset(str, 0, sizeof(str)); // Fill memory with a constant (e.g., zeroing an array)
memcpy(dest, src, n); // Copy raw memory blocks (faster than strcpy)
memcmp(s1, s2, n); // Compare raw memory blocks
Pointers
/* --- POINTERS & MEMORY (<stdlib.h>) --- */
int *ptr; // Pointer to an integer
ptr = &var; // Store address of var in ptr
*ptr = 10; // Dereference: change value at address to 10
int **dptr = &ptr; // Pointer to a pointer (Double Pointer)
// Array & Pointer Equivalence
arr[i] == *(arr + i); // Standard indexing vs pointer arithmetic
*(ptr + 1); // Moves to the next memory block (size of int)
// Dynamic Memory Allocation (The Heap)
ptr = (int*)malloc(n * sizeof(int)); // Allocate memory for n integers
ptr = (int*)calloc(n, sizeof(int)); // Allocate AND zero-initialize memory
ptr = realloc(ptr, new_size); // Resize previously allocated block
free(ptr); // Deallocate memory (prevent leaks!)
ptr = NULL; // Best practice: nullify after freeing
// Constants and Pointers
const int *p = &x; // Data is constant (cannot change *p)
int * const p = &x; // Pointer is constant (cannot change p)
// Special Pointers
void *vptr; // Generic pointer (can point to any type)
int (*f)(int); // Function pointer (points to a function)
if (ptr == NULL) // Null check: always verify before dereferencing
Memory Management
/* --- DYNAMIC MEMORY MANAGEMENT (<stdlib.h>) --- */
// Allocation Functions
void *ptr = malloc(size); // Allocate 'size' bytes (contains garbage values)
void *ptr = calloc(n, size); // Allocate n * size bytes (all bits set to 0)
void *ptr = realloc(old_ptr, s); // Resize block; may move to a new address
free(ptr); // Release memory back to the system
// Safety & Best Practices
if (ptr == NULL) { // ALWAYS check if allocation failed
perror("malloc failed");
exit(1);
}
// Avoiding Memory Leaks & Errors
free(ptr); // 1. Deallocate when finished
ptr = NULL; // 2. Prevent "Dangling Pointer" (pointing to freed memory)
// Memory Operations (<string.h>)
memset(ptr, 0, n * sizeof(int)); // Manually zero out a block
memcpy(dest, src, n); // Copy n bytes from src to dest
memmove(dest, src, n); // Safer copy if memory regions overlap
// Common Pitfalls
// 1. Memory Leak: Forgetting to free() before losing the pointer.
// 2. Double Free: Calling free() on the same pointer twice (causes crashes).
// 3. Buffer Overflow: Writing past the allocated size of the block.
Structures
// DEFINITION
struct Person {
char name[50];
int age;
};
// DECLARATION
struct Person p1;
p1.age = 25;
// WITH TYPEDEF
typedef struct {
int x, y;
} Point;
union Data {
int i;
float f;
char str[20]; // Only ONE member can be held at a time
};
// sizeof(union Data) is the size of its largest member (20 bytes)
Point p2 = { .y = 50, .x = 10 }; // Initialize by name, any order
File I/O
FILE *fp;
// OPEN MODES: "r" "w" "a" "r+" "w+" "a+"
fp = fopen("file.txt", "r");
// READ/WRITE
fprintf(fp, "%d", num); // Write
fscanf(fp, "%d", &num); // Read
fgetc(fp); // Read char
fputc('A', fp); // Write char
fgets(str, 100, fp); // Read line
fputs("text", fp); // Write string
fclose(fp); // Close file
/* --- ADVANCED FILE I/O --- */
// 1. ERROR CHECKING
if ((fp = fopen("file.txt", "r")) == NULL) {
perror("Error opening file"); // Prints system error message
}
// 2. BINARY READ/WRITE
// fwrite(data_ptr, size_of_element, count, fp);
fwrite(&struct_var, sizeof(struct_var), 1, fp);
fread(&struct_var, sizeof(struct_var), 1, fp);
// 3. FILE POSITIONING (SEEKING)
fseek(fp, 0, SEEK_END); // Move to end of file
long size = ftell(fp); // Get current position (useful for file size)
rewind(fp); // Move cursor back to start (offset 0)
// Origin options: SEEK_SET (start), SEEK_CUR (current), SEEK_END (end)
// 4. BUFFERING & STATUS
fflush(fp); // Force write buffered data to disk
feof(fp); // Returns non-zero if End-Of-File reached
ferror(fp); // Returns non-zero if error occurred
clearerr(fp); // Resets error and EOF indicators
// 5. FILE SYSTEM OPS
remove("old_file.txt"); // Delete a file
rename("old.txt", "new.txt"); // Rename a file
Preprocessor Directive
#include <stdio.h> // Search system directories
#include "my_file.h" // Search local directory first
#define PI 3.14159 // Constant macro
#define SQUARE(x) ((x) * (x)) // Function-like macro (use parentheses!)
#define MAX(a,b) ((a)>(b)?(a):(b))
// 1. CONDITIONAL COMPILATION
#if defined(WIN32) || defined(_WIN64)
#define PLATFORM "Windows"
#elif defined(__linux__)
#define PLATFORM "Linux"
#else
#define PLATFORM "Unknown"
#endif
// 2. HEADER GUARDS (Prevents double inclusion)
#ifndef MY_HEADER_H
#define MY_HEADER_H
// Header content here
#endif
// 3. PREDEFINED MACROS (Useful for debugging)
__FILE__ // Current file name (string)
__LINE__ // Current line number (int)
__DATE__ // Compilation date (string)
__TIME__ // Compilation time (string)
__func__ // Current function name (string, C99)
// 4. STRINGIFICATION & CONCATENATION
#define TO_STR(x) #x // Converts x to "x"
#define CONCAT(a, b) a##b // Joins a and b into one token
// 5. ERROR & PRAGMA
#error "ErrorMessage" // Stops compilation with a message
#pragma once // Modern alternative to header guards
#undef PI // Removes macro definition
Math Functions (#include <math.h>)
pow(x, y) // x^y
sqrt(x) // Square root
abs(x) // Absolute value
ceil(x) // Round up
floor(x) // Round down
sin(x) cos(x) tan(x)
log(x) log10(x)
<stdio.h> // I/O functions
<stdlib.h> // Memory, conversion, random
<string.h> // String operations
<math.h> // Math functions
<ctype.h> // Character functions
<time.h> // Time/date functions
<stdbool.h> // Boolean type
<limits.h> // Type limits (INT_MAX, etc.)
TYPEDEF & ENUM
// TYPEDEF
typedef unsigned long ulong;
typedef int* intptr;
// ENUM
enum Day {SUN, MON, TUE, WED, THU, FRI, SAT};
enum Day today = MON;
USEFUL SNIPPETS
// SWAP TWO NUMBERS
temp = a; a = b; b = temp;
// TERNARY OPERATOR
max = (a > b) ? a : b;
// SIZEOF OPERATOR
size = sizeof(int); // Returns 4
// COMMAND LINE ARGUMENTS
int main(int argc, char *argv[]) { }
COMPILATION & EXECUTION
gcc program.c -o program # Compile
./program # Run
gcc -Wall -g program.c # Debug mode