labex.
io
C Programming Cheatsheet
Essential operations for C programming and development
This cheatsheet provides a quick reference to fundamental C syntax, concepts, and programming techniques, ideal for both beginners
and experienced programmers for efficient C development.
Basic Syntax Data Types Control Flow
Core language fundamentals Variables and type system Loops and conditionals
Functions Pointers & Arrays
Function definitions and calls Memory management basics
Basic Syntax & Structure
Hello World Program Main Function
Basic structure of a C program. Program entry point with return values.
#include <stdio.h> int main() {
// Program code here
int main() { return 0; // Success
printf("Hello, World!\n"); }
return 0;
} int main(int argc, char *argv[]) {
// argc: argument count
Headers & Preprocessor // argv: argument values (command line)
return 0;
Include libraries and use preprocessor directives. }
#include <stdio.h> // Standard input/output Basic Output
#include <stdlib.h> // Standard library
#include <string.h> // String functions Display text and variables to console.
#include <math.h> // Math functions
printf("Hello\n");
#define PI 3.14159 printf("Value: %d\n", 42);
#define MAX_SIZE 100 // Multiple values in one line
printf("Name: %s, Age: %d\n", name, age);
Comments
Basic Input
Single-line and multi-line comments.
Read user input from console.
// Single-line comment
int age;
/* char name[50];
Multi-line comment scanf("%d", &age);
spans multiple lines scanf("%s", name);
*/ // Read entire line with spaces
fgets(name, sizeof(name), stdin);
// TODO: Implement feature
/* FIXME: Bug in this section */
Data Types & Variables
Fundamental data types and variable declarations.
01 02 03
Primitive Types Arrays & Strings Constants & Modifiers
Basic data types for storing different kinds Arrays and string handling in C. Immutable values and storage modifiers.
of values.
// Arrays // Constants
// Integer types int numbers[5] = {1, 2, 3, 4, 5}; const int MAX_SIZE = 100;
int age = 25; int matrix[3][3] = {{1,2,3}, {4,5,6}, const double PI = 3.14159;
short small_num = 100; {7,8,9}};
long large_num = 1000000L; // Preprocessor constants
long long huge_num = // Strings (character arrays) #define BUFFER_SIZE 512
9223372036854775807LL; char name[50] = "John Doe"; #define TRUE 1
char greeting[] = "Hello"; #define FALSE 0
// Floating-point types char buffer[100]; // Uninitialized
float price = 19.99f; // Storage modifiers
double precise = 3.14159265359; // String length and size static int count = 0; // Static
int len = strlen(name); variable
// Character and boolean (using int) int size = sizeof(buffer); extern int global_var; // External
char grade = 'A'; variable
int is_valid = 1; // 1 for true, 0 for register int fast_var; // Register hint
false
Control Flow Structures
Conditional Statements While Loops
Make decisions based on conditions. Condition-based iteration.
// If-else statement // While loop
if (age >= 18) { int count = 0;
printf("Adult\n"); while (count < 5) {
} else if (age >= 13) { printf("%d\n", count);
printf("Teenager\n"); count++;
} else { }
printf("Child\n");
} // Do-while loop (executes at least once)
int input;
// Ternary operator do {
char* status = (age >= 18) ? "Adult" : "Minor"; printf("Enter a number (0 to quit): ");
scanf("%d", &input);
// Switch statement } while (input != 0);
switch (grade) {
case 'A': Loop Control
printf("Excellent!\n");
Break and continue statements.
break;
case 'B':
printf("Good job!\n"); for (int i = 0; i < 10; i++) {
break; if (i == 3) {
default: continue; // Skip iteration
printf("Keep trying!\n"); }
} if (i == 7) {
break; // Exit loop
For Loops }
printf("%d ", i);
Iterate with counter-based loops. }
// Traditional for loop // Nested loops with break
for (int i = 0; i < 10; i++) { for (int i = 0; i < 3; i++) {
printf("%d ", i); for (int j = 0; j < 3; j++) {
} if (i == j) break; // Break inner loop only
printf("%d,%d ", i, j);
// Array iteration }
int numbers[] = {1, 2, 3, 4, 5}; }
int size = sizeof(numbers) / sizeof(numbers[0]);
for (int i = 0; i < size; i++) {
printf("%d ", numbers[i]);
}
// Nested loops
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d,%d ", i, j);
}
}
Functions
Function Declaration & Definition Recursive Functions
Create reusable code blocks. Functions that call themselves.
// Function declaration (prototype) // Factorial calculation
int add(int a, int b); int factorial(int n) {
void printMessage(char* msg); if (n <= 1) {
return 1; // Base case
// Function definition }
int add(int a, int b) { return n * factorial(n - 1);
return a + b; }
}
// Fibonacci sequence
void printMessage(char* msg) { int fibonacci(int n) {
printf("%s\n", msg); if (n <= 1) {
} return n;
}
// Function call return fibonacci(n-1) + fibonacci(n-2);
int result = add(5, 3); }
printMessage("Hello, functions!");
Function Pointers
Passing Arrays to Functions
Pointers to functions for dynamic behavior.
Functions that work with arrays.
// Function pointer declaration
// Array as parameter (pointer) int (*operation)(int, int);
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) { // Assign function to pointer
printf("%d ", arr[i]); operation = add;
} int result = operation(5, 3);
printf("\n");
} // Array of function pointers
int (*operations[])(int, int) = {add, subtract, multiply};
// Modifying array elements result = operations[0](10, 5);
void doubleValues(int arr[], int size) {
for (int i = 0; i < size; i++) {
arr[i] *= 2;
}
}
Pointers & Memory Management
Understanding pointers and dynamic memory allocation.
Pointer Basics Dynamic Memory Allocation
Declare and use pointers to access memory addresses. Allocate and deallocate memory at runtime.
int x = 10; #include <stdlib.h>
int *ptr = &x; // Pointer to x
// Allocate memory for single integer
printf("Value of x: %d\n", x); int *ptr = (int*)malloc(sizeof(int));
printf("Address of x: %p\n", &x); if (ptr != NULL) {
printf("Value of ptr: %p\n", ptr); *ptr = 42;
printf("Value pointed by ptr: %d\n", *ptr); printf("Value: %d\n", *ptr);
free(ptr); // Always free allocated memory
// Modify value through pointer }
*ptr = 20;
printf("New value of x: %d\n", x); // Allocate array dynamically
int *arr = (int*)malloc(10 * sizeof(int));
// Null pointer if (arr != NULL) {
int *null_ptr = NULL; for (int i = 0; i < 10; i++) {
arr[i] = i * i;
Arrays and Pointers }
free(arr);
Relationship between arrays and pointers. }
int arr[5] = {1, 2, 3, 4, 5}; String Pointers
int *p = arr; // Points to first element
Working with strings and character pointers.
// Array notation vs pointer arithmetic
printf("%d\n", arr[2]); // Array notation // String literals and pointers
printf("%d\n", *(p + 2)); // Pointer arithmetic char *str1 = "Hello"; // String literal
printf("%d\n", p[2]); // Pointer as array char str2[] = "World"; // Character array
char *str3 = (char*)malloc(20); // Dynamic string
// Iterate using pointer
for (int i = 0; i < 5; i++) { // String functions
printf("%d ", *(p + i)); strcpy(str3, "Dynamic");
} printf("Length: %lu\n", strlen(str1));
printf("Compare: %d\n", strcmp(str1, str2));
strcat(str2, "!");
// Always free dynamic strings
free(str3);
Structures and User-Defined Types
Structure Definition Pointers to Structures
Define custom data types with multiple fields. Use pointers to access and modify structures.
// Structure definition Student *student_ptr = &student1;
struct Rectangle {
double width; // Access using pointer (two methods)
double height; printf("Name: %s\n", (*student_ptr).name);
}; printf("Age: %d\n", student_ptr->age);
// Structure with typedef // Modify through pointer
typedef struct { student_ptr->age = 21;
char name[50]; strcpy(student_ptr->name, "Alice Johnson");
int age;
double gpa; // Dynamic structure allocation
} Student; Student *new_student =
(Student*)malloc(sizeof(Student));
// Create and initialize structures if (new_student != NULL) {
struct Rectangle rect1 = {5.0, 3.0}; strcpy(new_student->name, "Bob");
Student student1 = {"Alice", 20, 3.75}; new_student->age = 19;
new_student->gpa = 3.2;
// Access structure members free(new_student);
printf("Area: %.2f\n", [Link] * [Link]); }
printf("Student: %s, Age: %d\n", [Link],
[Link]); Unions and Enums
Alternative data organization methods.
Nested Structures
Structures containing other structures. // Union - shared memory space
union Data {
typedef struct { int integer;
int day, month, year; float floating;
} Date; char character;
};
typedef struct {
char name[50]; union Data data;
Date birthdate; [Link] = 42;
double salary; printf("Integer: %d\n", [Link]);
} Employee;
// Enumeration
Employee emp = { enum Weekday {
"John Smith", MONDAY, TUESDAY, WEDNESDAY,
{15, 6, 1985}, THURSDAY, FRIDAY, SATURDAY, SUNDAY
50000.0 };
};
enum Weekday today = FRIDAY;
printf("Born: %d/%d/%d\n", printf("Today is day %d\n", today);
[Link],
[Link],
[Link]);
File Input/Output Operations
Handle file reading, writing, and manipulation.
File Reading File Writing
Read data from text files. Write data to text files.
#include <stdio.h> // Write to file
FILE *outfile = fopen("[Link]", "w");
// Read entire file character by character if (outfile != NULL) {
FILE *file = fopen("[Link]", "r"); fprintf(outfile, "Hello, file!\n");
if (file != NULL) { fprintf(outfile, "Number: %d\n", 42);
int ch; fclose(outfile);
while ((ch = fgetc(file)) != EOF) { }
putchar(ch);
} // Append to existing file
fclose(file); FILE *appendfile = fopen("[Link]", "a");
} if (appendfile != NULL) {
fprintf(appendfile, "New log entry\n");
// Read line by line fclose(appendfile);
FILE *file2 = fopen("[Link]", "r"); }
char buffer[256];
while (fgets(buffer, sizeof(buffer), file2) != NULL) { // Write array to file
printf("Line: %s", buffer); int numbers[] = {1, 2, 3, 4, 5};
} FILE *numfile = fopen("[Link]", "w");
fclose(file2); for (int i = 0; i < 5; i++) {
fprintf(numfile, "%d ", numbers[i]);
// Read formatted data }
FILE *numbers = fopen("[Link]", "r"); fclose(numfile);
int num;
while (fscanf(numbers, "%d", &num) == 1) { Binary File Operations
printf("Number: %d\n", num);
} Read and write binary data efficiently.
fclose(numbers);
// Write binary data
Error Checking Student students[3] = {
{"Alice", 20, 3.75},
Handle file operations safely. {"Bob", 21, 3.2},
{"Charlie", 19, 3.9}
FILE *file = fopen("[Link]", "r"); };
if (file == NULL) {
printf("Error opening file!\n"); FILE *binfile = fopen("[Link]", "wb");
perror("fopen"); // Print system error message fwrite(students, sizeof(Student), 3, binfile);
return 1; fclose(binfile);
}
// Read binary data
// Check for read errors Student loaded_students[3];
if (ferror(file)) { FILE *readbin = fopen("[Link]", "rb");
printf("Error reading file!\n"); fread(loaded_students, sizeof(Student), 3, readbin);
} fclose(readbin);
// Check for end of file
if (feof(file)) {
printf("Reached end of file\n");
}
fclose(file);
String Manipulation
Essential string handling functions and techniques.
String Functions String Conversion
Common string operations from string.h library. Convert strings to numbers and vice versa.
#include <string.h> #include <stdlib.h>
char str1[50] = "Hello"; // String to number conversion
char str2[] = "World"; char num_str[] = "12345";
char dest[100]; char float_str[] = "3.14159";
// String length int num = atoi(num_str);
int len = strlen(str1); long long_num = atol(num_str);
printf("Length: %d\n", len); double float_num = atof(float_str);
// String copy printf("Integer: %d\n", num);
strcpy(dest, str1); printf("Long: %ld\n", long_num);
strncpy(dest, str1, 10); // Copy first 10 chars printf("Double: %.2f\n", float_num);
// String concatenation // Number to string (using sprintf)
strcat(dest, " "); char buffer[50];
strcat(dest, str2); sprintf(buffer, "%d", 42);
strncat(dest, "!", 1); // Append 1 character sprintf(buffer, "%.2f", 3.14159);
printf("String: %s\n", buffer);
// String comparison
int result = strcmp(str1, str2); Custom String Processing
if (result == 0) {
Manual string manipulation techniques.
printf("Strings are equal\n");
}
// Count characters in string
String Searching int countChar(char *str, char target) {
int count = 0;
Find substrings and characters within strings. while (*str) {
if (*str == target) count++;
char text[] = "The quick brown fox"; str++;
char *ptr; }
return count;
// Find first occurrence of character }
ptr = strchr(text, 'q');
if (ptr != NULL) { // Reverse string in place
printf("Found 'q' at position: %ld\n", ptr - text); void reverseString(char *str) {
} int len = strlen(str);
for (int i = 0; i < len/2; i++) {
// Find last occurrence char temp = str[i];
ptr = strrchr(text, 'o'); str[i] = str[len-1-i];
printf("Last 'o' at position: %ld\n", ptr - text); str[len-1-i] = temp;
}
// Find substring }
ptr = strstr(text, "brown");
if (ptr != NULL) {
printf("Found 'brown' at: %s\n", ptr);
}
Compilation & Build Process
Compile and build C programs efficiently.
GCC Compilation C Standards Makefile Basics
GNU Compiler Collection for C. Compile with specific C standard Automate compilation with make
versions. utility.
# Basic compilation
gcc -o program main.c # C90/C89 standard (ANSI C) # Simple Makefile
gcc -std=c89 -o program main.c CC = gcc
# With debugging information CFLAGS = -std=c11 -Wall -g
gcc -g -o program main.c # C99 standard TARGET = program
gcc -std=c99 -o program main.c SOURCES = main.c utils.c
# Optimization levels
gcc -O2 -o program main.c # C11 standard (recommended) $(TARGET): $(SOURCES)
gcc -std=c11 -o program main.c $(CC) $(CFLAGS) -o
# Multiple source files $(TARGET) $(SOURCES)
gcc -o program main.c utils.c # C18 standard (latest)
math.c gcc -std=c18 -o program main.c clean:
rm -f $(TARGET)
# Include additional directories # Enable all warnings
gcc -I/usr/local/include -o gcc -Wall -Wextra -std=c11 -o .PHONY: clean
program main.c program main.c
# Link libraries
gcc -o program main.c -lm -
lpthread
Best Practices & Tips
Write clean, efficient, and maintainable C code.
Naming Conventions Performance Tips
Consistent naming makes code more readable. Write efficient C code.
// Variables and functions: snake_case // Use appropriate data types
int student_count; char small_num = 10; // For small values
double calculate_average(int scores[], int size); int normal_num = 1000; // For typical integers
// Constants: UPPER_CASE // Minimize function calls in loops
#define MAX_BUFFER_SIZE 1024 int len = strlen(str); // Calculate once
#define PI 3.14159 for (int i = 0; i < len; i++) {
// Process string
// Structures: PascalCase or snake_case }
typedef struct {
char name[50]; // Use register for frequently accessed variables
int age; register int counter;
} Student;
// Prefer arrays over dynamic allocation when size is
// Global variables: prefix with g_ known
int g_total_count = 0; int fixed_array[100]; // Stack allocation
// vs
// Function parameters: clear names int *dynamic_array = malloc(100 * sizeof(int));
void process_data(int *input_array, int array_size);
Code Organization
Memory Safety
Structure code for maintainability.
Prevent common memory-related bugs.
// Header file (utils.h)
// Always initialize variables #ifndef UTILS_H
int count = 0; // Good #define UTILS_H
int count; // Dangerous - uninitialized
// Function prototypes
// Check malloc return value double calculate_area(double radius);
int *ptr = malloc(sizeof(int) * 10); int fibonacci(int n);
if (ptr == NULL) {
printf("Memory allocation failed!\n"); // Structure definitions
return -1; typedef struct {
} int x, y;
} Point;
// Always free allocated memory
free(ptr); #endif // UTILS_H
ptr = NULL; // Prevent accidental reuse
// Implementation file (utils.c)
// Array bounds checking #include "utils.h"
for (int i = 0; i < array_size; i++) { #include <math.h>
// Safe array access
array[i] = i; double calculate_area(double radius) {
} return M_PI * radius * radius;
}
Reference: This cheatsheet covers essential C programming commands and modern practices for efficient software development.
[Link]