C Programming Language Cheatsheet
Table of Contents
Basic Structure
Program Template
/* comment to describe the program */
#include <stdio.h>
/* definitions */
int main(int argc, char **argv) {
/* variable declarations */
/* program statements */
}
Naming Conventions
Variable names must follow these rules:
- Can contain uppercase letters (A to Z)
- Can contain lowercase letters (a to z)
- Can contain numbers (0 to 9)
- Can contain underscores (_)
- Cannot start with a number
- Are case-sensitive
Variables and Data Types
Basic Data Types
Data Type |
Description |
Example Usage |
int |
Integer values |
int count = -1; |
char |
Character values |
char letter = 'A'; |
float |
Floating point numbers |
float pi = 3.141f; |
double |
Double precision numbers |
double precise_pi = 3.14159265359; |
Variable Declaration Examples
int age;
char initial;
float temperature;
double precise_measurement;
int *pointer_to_int;
char string_array[50];
Memory Management
Dynamic Memory Allocation
// Allocating memory
int *array = (int *) malloc(sizeof(int) * 10);
if (array == NULL) {
/* handle allocation failure */
}
// Resizing memory
int *newarray = (int *) realloc(array, sizeof(int) * 20);
if (newarray == NULL) {
/* handle reallocation failure */
}
array = newarray;
// Freeing memory
free(array);
Memory Management Best Practices
- Always check for NULL after malloc/realloc
- Always free allocated memory when no longer needed
- Never free memory more than once
- Update pointers after reallocation
- Initialize pointers to NULL when declaring
Binary Operators
Bitwise Operations
Operator |
Description |
Example |
a & b |
Bitwise AND |
result = 5 & 3; |
a | b |
Bitwise OR |
result = 5 \| 3; |
a ^ b |
Bitwise XOR |
result = 5 ^ 3; |
a << n |
Left shift |
result = 5 << 2; |
a >> n |
Right shift |
result = 5 >> 2; |
Assignment Shortcuts
Compound Assignment Operators
Operator |
Equivalent |
Example |
+= |
a = a + b |
a += b; |
-= |
a = a - b |
a -= b; |
*= |
a = a * b |
a *= b; |
/= |
a = a / b |
a /= b; |
%= |
a = a % b |
a %= b; |
Standard Streams
Stream |
Description |
Usage |
stdin |
Standard input |
Reading user input |
stdout |
Standard output |
Normal program output |
stderr |
Standard error |
Error messages |
File Operations
FILE *fopen(char *filename, char *mode);
size_t fread(void *ptr, size_t size, size_t nitems, FILE *stream);
int fclose(FILE *stream);
// String output
int puts(char *string);
int printf(char *format, ...);
int fprintf(FILE *stream, char *format);
int sprintf(char *string, char *format);
// Character input/output
int getc(FILE *stream);
int putc(int ch, FILE *stream);
int getchar(void);
int putchar(int ch);
Standard Library Functions
Memory Management Functions
void *malloc(size_t size);
void *realloc(void *ptr, size_t newsize);
void free(void *ptr);
Sorting and Searching
void qsort(void *array, size_t nitems, size_t size,
int (*compar)(void *a, void *b));
void *bsearch(void *key, void *array, size_t nitems,
size_t size, int (*compar)(void *a, void *b));
Random Number Generation
void srand(unsigned int seed);
int rand(void);
Best Practices
Memory Management Guidelines
- Always initialize variables before use
- Check return values from memory allocation functions
- Free dynamically allocated memory
- Avoid memory leaks
- Use appropriate data types for variables
Code Organization
- Include necessary header files at the start
- Define constants and macros after headers
- Declare global variables (if needed) after definitions
- Define functions before use or provide prototypes
- Use meaningful variable and function names
Error Handling
- Always check return values of system calls
- Use stderr for error messages
- Implement proper error recovery mechanisms
- Clean up resources in error conditions
- Use appropriate error codes
Advanced Topics
Function Pointers
// Declaration of a function pointer
int (*operation)(int, int);
// Example usage
int add(int a, int b) {
return a + b;
}
operation = &add;
int result = (*operation)(5, 3);
Structures and Unions
struct Point {
int x;
int y;
};
union Data {
int i;
float f;
char str[20];
};
Preprocessor Directives
#define MAX_SIZE 100
#define SQUARE(x) ((x) * (x))
#ifdef DEBUG
// Debug code
#endif
#ifndef HEADER_H
#define HEADER_H
// Header content
#endif
Type Definitions
typedef unsigned long ulong;
typedef struct Point Point;
typedef void (*CallbackFunc)(void *data);
Bit Fields
struct Flags {
unsigned int is_active : 1;
unsigned int is_urgent : 1;
unsigned int priority : 3;
};
Common Programming Patterns
Buffer Management
#define BUFFER_SIZE 1024
char buffer[BUFFER_SIZE];
size_t bytes_read;
// Safe reading
if ((bytes_read = fread(buffer, 1, BUFFER_SIZE - 1, file)) > 0) {
buffer[bytes_read] = '\0';
}
String Manipulation
// String copy with bounds checking
char dest[50];
const char *src = "Hello, World!";
strncpy(dest, src, sizeof(dest) - 1);
dest[sizeof(dest) - 1] = '\0';
Command Line Arguments
int main(int argc, char **argv) {
for (int i = 1; i < argc; i++) {
printf("Argument %d: %s\n", i, argv[i]);
}
return 0;
}
Debugging Tips
Common Debugging Techniques
- Use printf debugging
- Check return values
- Validate pointer operations
- Monitor memory usage
- Use assert statements
Assert Usage
#include <assert.h>
void process_data(int *data, size_t size) {
assert(data != NULL);
assert(size > 0);
// Process data
}
Optimization Techniques
- Use appropriate data structures
- Minimize memory allocation
- Optimize loops
- Use bitwise operations when applicable
- Consider cache efficiency
Example Optimizations
// Optimized loop
for (int i = 0; i < size; i++) {
// Cache the value to avoid multiple array accesses
int temp = array[i];
if (temp > max) {
max = temp;
}
}