C Language Cheat Sheet

Structure of a C Program

#include <stdio.h>

int main() {
    printf("Hello, World!\n");
    return 0;
}

Header Files and Preprocessors

Used for including libraries, defining constants, and conditionally compiling code.

#include <stdio.h>

#define PI 3.14

#ifdef DEBUG
printf("Debug mode\n");
#endif

main() Function

int main() {
    // Your code here
    return 0;
}

Comments (// and /* */)

// Single-line comment
/* Multi-line
   comment */

Variables and Data Types

int i;
float f;
char c;
double d;
short s;
long l;

Constants and Macros

#define is used to create macros (text replacements), while const defines typed constants with scope and type checking.

#define PI 3.1415
const int MAX = 100;

Input and Output (scanf, printf)

The scanf and printf functions in C are used for reading input and displaying output. They rely on format specifiers like %d for integers and %s for strings.

#include <stdio.h>

int main() {
  int x;
  printf("Enter a number: ");
  scanf("%d", &x);
  printf("You entered: %d
", x);
  return 0;
}

Operators

Arithmetic Operators

int a = 10, b = 20;

a + b   // 30
a - b   // -10
a * b   // 200
b / a   // 2
b % a   // 0

Relational Operators

int a = 10, b = 20;

a == b   // false
a != b   // true
a > b    // false
a < b    // true
a >= b   // false
a <= b   // true

Logical Operators

int a = 10, b = 20;

(a < b) && (a > 5)   // true
(a > b) || (b == 20) // true
!(a == b)            // true

Assignment Operators

int a = 10;

a += 5   // a = 15
a -= 3   // a = 12
a *= 2   // a = 24
a /= 4   // a = 6
a %= 4   // a = 2

Increment / Decrement Operators

int a = 10;

a++   // a becomes 11
++a   // a becomes 12
a--   // a becomes 11
--a   // a becomes 10

Conditional (Ternary) Operator

int a = 10, b = 20;

int max = (a > b) ? a : b;  // max = 20

Bitwise Operators

int a = 10, b = 4;

a & b   // 0
a | b   // 14
a ^ b   // 14
~a      // -11
a << 1  // 20
a >> 1  // 5

Other Operators

sizeof(int)      // 4 (on most systems)
(float) a        // Casts int a to float

Control Flow

if / else

int x = 3;

if (x > 0) {
  printf("Positive");
} else {
  printf("Non-positive");
}

switch / case

int day = 1;

switch (day) {
  case 1: printf("Mon"); break;
  case 2: printf("Tue"); break;
  default: printf("Other");
}

for Loop

for (int i = 0; i < 5; i++) {
  printf("%d ", i);
}

while / do-while

int x = 0;

while (x < 5) {
  x++;
}

do {
  x--;
} while (x > 0);

break / continue

for (int i = 0; i < 10; i++) {
  if (i == 5) break;
  if (i % 2 == 0) continue;
  printf("%d ", i);
}

goto

goto label;

printf("This will be skipped.");

label:
printf("Jumped here");

Functions

Function declaration and definition:

int add(int a, int b) {
  return a + b;
}

Call by value passes a copy of the variable:

void change(int a) {
  a = 10;
}

Call by reference uses pointers to modify the original value:

void changePtr(int *a) {
  *a = 10;
}

Recursive function example (factorial):

int factorial(int n) {
  if (n == 0) return 1;
  return n * factorial(n - 1);
}

Arrays

Declaring and initializing an integer array:

int arr[5] = {1, 2, 3, 4, 5};

Accessing and modifying array elements by index:

arr[2] = 10;
printf("%d", arr[2]);

Traversing an array using a loop:

for (int i = 0; i < 5; i++) {
  printf("%d ", arr[i]);
}

Strings

String declaration using character array:

char str[] = "Hello";

Calculate the length of a string:

size_t len = strlen(str);

Copy one string into another:

char dest[100];
strcpy(dest, str);

Compare two strings:

int result = strcmp(str, "World");

Pointers

Basic pointer declaration and dereferencing:

int x = 10;
int *p = &x;
printf("%d", *p);

Pointer arithmetic allows navigation through contiguous memory locations:

int arr[3] = {1, 2, 3};
int *p = arr;
p++;

Pointers can reference arrays directly as the array name represents the address of its first element:

int arr[3] = {1, 2, 3};
int *ptr = arr;
printf("%d", ptr[0]);

Function pointers store the address of a function and can be used to call it:

void greet() {
  printf("Hello");
}

void (*fptr)() = greet;
fptr();

Pointers can be used to handle strings as character arrays:

char *msg = "Hello";
printf("%s", msg);

Memory Management

Allocate memory dynamically using malloc:

int *p = (int*) malloc(sizeof(int));
*p = 5;

Allocate zero-initialized memory for an array using calloc:

int *arr = (int*) calloc(5, sizeof(int));

Resize previously allocated memory using realloc:

arr = (int*) realloc(arr, 10 * sizeof(int));

Free dynamically allocated memory to prevent memory leaks:

free(p);
free(arr);

Structures & Unions

Structures group variables of different types under one name:

struct Person {
  char name[50];
  int age;
};

Structures can be nested to model more complex data:

struct Company {
  struct Person CEO;
};

Unions share memory for all members, storing only one at a time:

union Data {
  int i;
  float f;
};

Enums define symbolic names for integer values:

enum color { RED, GREEN, BLUE };

File Handling

Opening a file for writing and writing data to it:

FILE *fp = fopen("file.txt", "w");
fprintf(fp, "Hello");
fclose(fp);

Opening a file for reading and reading from it:

FILE *fp = fopen("file.txt", "r");
char str[100];
fscanf(fp, "%s", str);
fclose(fp);

Seeking to the end of a file, getting its size, and rewinding to the beginning:

FILE *fp = fopen("file.txt", "r");
fseek(fp, 0, SEEK_END);
long size = ftell(fp);
rewind(fp);

Miscellaneous

Command-line arguments are passed to main() as parameters:

int main(int argc, char *argv[]) {
  printf("%s", argv[0]);
}

Preprocessor directives are evaluated before compilation:

#define MAX 100

#ifdef MAX
  printf("Defined");
#endif

Error handling using perror() from errno.h:

#include <errno.h>

perror("Error");

Storage classes define the scope and lifetime of variables:

auto int a;
register int r;
static int s;
extern int e;

Commonly used standard C library headers:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>