Skip to main content

C Programming Cheatsheet: Complete Syntax & Reference ๐Ÿš€

Mentor's Note: Think of this cheatsheet as a pocket translation dictionary. When you travel to a new country, you don't read the whole dictionary to order food; you look up the word you need. Similarly, when you are coding in the lab or prepping for exams, use this page to look up syntax instantly! ๐Ÿ’ก

๐Ÿ“š Board & Exam Relevance: This reference sheet covers the entire syntax required for GSEB Class 10/12 practicals, CBSE Computer Science, and university courses (BCA/B.Tech Sem-1).

What You'll Learn

By the end of this cheatsheet, you'll have instant access to:

  • The standard C skeleton and its compilation phases.
  • Primary data types, memory sizes, and format specifiers.
  • Control flow templates (if-else, loops, switch).
  • Functions, arrays, strings, pointers, and dynamic memory.
  • Structs vs Unions differences and file handling modes.

๐ŸŒŸ The Scenario: The Coding Pocket Dictionaryโ€‹

Imagine you are writing code during a board exam or a lab test. Your logic is perfect, but you cannot remember if strcpy takes the destination string first or the source string first. Instead of guessing and getting compiler errors, you open this cheatsheet, search strcpy, and find the answer in three seconds.

  • The Logic: Syntax translation at a glance! ๐Ÿ“–
  • The Result: Less memorization, faster debugging, and stress-free coding. โœ…

๐Ÿ’ป Basic C Skeleton & Compilation Flowโ€‹

Every C program requires a specific template to compile and run. Here is the minimum code needed:

#include <stdio.h> // Preprocessor directive to include standard input/output functions

// Main entry point where the operating system starts execution
int main() {
printf("Hello, VD Docs!\n"); // Print message on screen
return 0; // Return status 0 to OS (indicates successful execution)
}

// Output:
// Hello, VD Docs!

The Compilation Processโ€‹

C is a compiled language. Your human-readable code goes through four distinct stages to become machine-readable machine code:

  1. Preprocessing: Processes directives (lines starting with #), expands macros, and includes headers.
  2. Compilation: Translates the preprocessed file into assembly language.
  3. Assembly: Translates assembly code into machine-readable object code (.o or .obj file).
  4. Linking: Combines object files with system library code (like <stdio.h>) to produce a final executable.

๐Ÿ“Š Data Types & Format Specifiersโ€‹

C requires you to declare the type of data a variable holds. Here is a cheat-table of the primary data types:

Data TypeTypical Size (64-bit GCC)Range (Approx.)Format SpecifierExample Declaration
char1 Byte-128 to 127%cchar letter = 'A';
int4 Bytes-2 x 10โน to 2 x 10โน%d or %iint count = 105;
unsigned int4 Bytes0 to 4 x 10โน%uunsigned int age = 18;
short int2 Bytes-32,768 to 32,767%hdshort int temp = -5;
long int8 Bytes-9 x 10ยนโธ to 9 x 10ยนโธ%ldlong int dist = 987654321L;
float4 Bytes6 decimal places%f or %gfloat price = 99.99f;
double8 Bytes15 decimal places%lfdouble pi = 3.14159265359;
String (Char Array)1 Byte per charN/A%schar name[] = "Surat";
Pointer Address8 BytesMemory address%pint *ptr = &count;
size_t8 Bytes0 to max size%zusize_t len = sizeof(int);
The Floating-Point Gotcha

By default, any decimal constant (like 3.14) is treated as a double. If you assign it to a float variable, append f (e.g., 3.14f) to prevent truncation warnings.

Input/Output Exampleโ€‹

#include <stdio.h>

int main() {
int rollNo = 45;
float percentage = 92.4f;
char grade = 'A';

printf("Roll No: %d, Percentage: %.1f%%, Grade: %c\n", rollNo, percentage, grade);
return 0;
}

// Output:
// Roll No: 45, Percentage: 92.4%, Grade: A

๐Ÿ›ค๏ธ Control Flow Templatesโ€‹

1. Conditionals (if-else & Ternary)โ€‹

#include <stdio.h>

int main() {
int marks = 45;

// if-else-if ladder
if (marks >= 70) {
printf("Distinction\n");
} else if (marks >= 33) {
printf("Pass\n");
} else {
printf("Fail\n");
}

// Ternary Operator: (condition) ? true_expression : false_expression
char* result = (marks >= 33) ? "Pass" : "Fail";
printf("Status: %s\n", result);

return 0;
}

// Output:
// Pass
// Status: Pass

2. Switch Caseโ€‹

Best when checking a single integer or char variable against multiple fixed options.

#include <stdio.h>

int main() {
char grade = 'B';

switch (grade) {
case 'A':
printf("Excellent!\n");
break;
case 'B':
printf("Good Job!\n");
break;
case 'C':
printf("Passed\n");
break;
default:
printf("Invalid grade\n");
}
return 0;
}

// Output:
// Good Job!
Forget Break, Fall Through!

If you omit the break statement after a case, execution will continue into the next case statement (fall-through). Always check your break statements.

3. Loops (for, while, do-while)โ€‹

#include <stdio.h>

int main() {
// 1. For Loop: When number of iterations is known
printf("For Loop: ");
for (int i = 1; i <= 3; i++) {
printf("%d ", i);
}

// 2. While Loop: When loop condition dictates entry
printf("\nWhile Loop: ");
int count = 1;
while (count <= 3) {
printf("%d ", count);
count++;
}

// 3. Do-While Loop: Always executes at least once
printf("\nDo-While Loop: ");
int num = 1;
do {
printf("%d ", num);
num++;
} while (num <= 3);
printf("\n");

return 0;
}

// Output:
// For Loop: 1 2 3
// While Loop: 1 2 3
// Do-While Loop: 1 2 3

๐Ÿงฉ Functions & Scope Referenceโ€‹

A function is a block of code designed to perform a specific task.

Prototype, Definition & Callโ€‹

#include <stdio.h>

// 1. Function Declaration / Prototype (Tells compiler parameters and return type)
int addNumbers(int a, int b);

int main() {
// 2. Function Call (Arguments are passed by value)
int sum = addNumbers(5, 7);
printf("Sum: %d\n", sum);
return 0;
}

// 3. Function Definition (Actual body)
int addNumbers(int a, int b) {
return a + b; // Return statement must match return type
}

// Output:
// Sum: 12

Call by Value vs Call by Referenceโ€‹

  • Call by Value: Passes a copy of the argument. Changing the parameter inside the function does not affect the original variable.
  • Call by Reference: Passes the memory address of the argument (using pointers). Modifying the parameter changes the original variable.
#include <stdio.h>

void modifyValue(int val) {
val = 100; // Only changes the local copy
}

void modifyReference(int *ref) {
*ref = 100; // Directly changes the original variable in memory
}

int main() {
int x = 10;

modifyValue(x);
printf("Value check: x = %d\n", x);

modifyReference(&x);
printf("Reference check: x = %d\n", x);

return 0;
}

// Output:
// Value check: x = 10
// Reference check: x = 100

๐Ÿ—๏ธ Array & String Manipulation Gridโ€‹

An array is a collection of variables of the same type stored in contiguous memory locations.

Array Implementationsโ€‹

#include <stdio.h>

int main() {
// 1D Array initialization
int numbers[5] = {10, 20, 30, 40, 50};

// 2D Array (Matrix) initialization
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};

printf("1D Index 2: %d\n", numbers[2]);
printf("2D Row 1 Col 2: %d\n", matrix[1][2]);
return 0;
}

// Output:
// 1D Index 2: 30
// 2D Row 1 Col 2: 6

Strings (Character Arrays)โ€‹

In C, a string is simply a character array that terminates with a special character '\0' (null terminator).

#include <stdio.h>
#include <string.h> // Required for string helper functions

int main() {
char greeting[20] = "Hello";
char name[] = "Surat";

// 1. Length of string (excludes '\0')
printf("Length: %zu\n", strlen(greeting));

// 2. Concatenate (appends name to greeting)
strcat(greeting, " ");
strcat(greeting, name);
printf("Concatenated: %s\n", greeting);

// 3. String Compare (returns 0 if identical)
int result = strcmp(name, "Surat");
printf("Compare Result: %d\n", result);

// 4. String Copy (copies "Welcome" to greeting)
strcpy(greeting, "Welcome");
printf("Copied: %s\n", greeting);

return 0;
}

// Output:
// Length: 5
// Concatenated: Hello Surat
// Compare Result: 0
// Copied: Welcome
String FunctionSyntaxDescription
strlen(str)size_t strlen(const char *str)Returns the actual number of characters in str
strcpy(dest, src)char *strcpy(char *dest, const char *src)Copies source string to destination
strcat(dest, src)char *strcat(char *dest, const char *src)Appends source string onto the end of destination
strcmp(str1, str2)int strcmp(const char *str1, const char *str2)Returns 0 if equal, < 0 if str1 < str2, > 0 if str1 > str2
strchr(str, ch)char *strchr(const char *str, int ch)Finds the first occurrence of character ch
strstr(str, sub)char *strstr(const char *str, const char *sub)Finds the first occurrence of substring sub

๐ŸŽฏ Pointers & Memory Referenceโ€‹

A pointer is a variable that stores the memory address of another variable.

  • & (Address-of operator): Retrieves the memory address.
  • * (Dereference/Value-at-address operator): Accesses the data stored at a memory address.
#include <stdio.h>

int main() {
int age = 21;
int *ptr = &age; // Declaring a pointer and assigning age's memory address

printf("Value of age: %d\n", age);
printf("Address of age: %p\n", (void*)&age);
printf("Address stored in ptr: %p\n", (void*)ptr);
printf("Value dereferenced by ptr: %d\n", *ptr);

return 0;
}

// Output:
// Value of age: 21
// Address of age: 0x7ffeefbff56c
// Address stored in ptr: 0x7ffeefbff56c
// Value dereferenced by ptr: 21
Address Output format

The actual hexadecimal addresses will vary each time you run the program because the operating system dynamically allocates virtual memory addresses.

Dynamic Memory Allocation (<stdlib.h>)โ€‹

When you do not know the size of data before running the program, use dynamic memory allocation to grab memory from the Heap.

FunctionSignatureDescription
malloc()void* malloc(size_t size)Allocates uninitialized memory. Contains garbage values.
calloc()void* calloc(size_t num, size_t size)Allocates memory initialized to zero.
realloc()void* realloc(void *ptr, size_t new_size)Resizes previously allocated memory block.
free()void free(void *ptr)Deallocates heap memory to avoid memory leaks.
#include <stdio.h>
#include <stdlib.h> // Required for dynamic memory management

int main() {
// Allocate space for 3 integers dynamically
int *arr = (int *)malloc(3 * sizeof(int));

if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}

// Assign values
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;

printf("Dynamic Array Index 1: %d\n", arr[1]);

// Free memory to prevent memory leaks
free(arr);

return 0;
}

// Output:
// Dynamic Array Index 1: 20

๐Ÿ›๏ธ Structs vs Unions Comparison Checklistโ€‹

Both structures (struct) and unions (union) let you group variables of different data types together. However, their internal memory layout is completely different.

Syntax Check-Gridโ€‹

=== "Structure (struct)"

#include <stdio.h>

struct Student {
int rollNo;
char name[20];
float marks;
};

int main() {
struct Student s = {1, "Raj", 85.5f};
printf("Struct Name: %s, Roll No: %d\n", s.name, s.rollNo);
return 0;
}

// Output:
// Struct Name: Raj, Roll No: 1

=== "Union (union)"

#include <stdio.h>

union Data {
int intVal;
float floatVal;
char charVal;
};

int main() {
union Data d;
d.intVal = 42;
printf("Union intVal: %d\n", d.intVal);
return 0;
}

// Output:
// Union intVal: 42

Layout Comparisonโ€‹

Struct Memory Layout (All variables live in separate locations):
+-------------------+----------------------+-------------------+
| rollNo (4 bytes) | name (20 bytes) | marks (4 bytes) |
+-------------------+----------------------+-------------------+
Total Size = 4 + 20 + 4 = 28 bytes (plus potential compiler padding)

Union Memory Layout (All variables share the exact same location):
+--------------------------------------------------------------+
| name / floatVal / intVal |
+--------------------------------------------------------------+
Total Size = Largest member (name = 20 bytes)

Side-by-Side Checklistโ€‹

FeatureStructure (struct)Union (union)
Memory AllocationAllocates distinct memory addresses for every member.Allocates a single shared memory block matching the largest member.
SizeSum of sizes of all members (plus padding).Equal to the size of the largest member.
Member AccessYou can access all members at the same time.Only one member can contain a valid value at any given time.
Access Operator. (dot) for objects, -> (arrow) for pointers.. (dot) for objects, -> (arrow) for pointers.

โš™๏ธ Preprocessor Macros & Rulesโ€‹

Preprocessor directives are processed before your code goes to the actual compiler. They do not end with semicolons.

  • Object-like macros: Replacing simple constants.
  • Function-like macros: Replacing small inline helper functions (always wrap arguments in parentheses to avoid evaluation bugs).
#include <stdio.h>

#define PI 3.14159 // Object-like macro
#define AREA_OF_CIRCLE(r) (PI * (r) * (r)) // Function-like macro

int main() {
float radius = 5.0f;
float area = AREA_OF_CIRCLE(radius);

printf("Area: %.2f\n", area);
return 0;
}

// Output:
// Area: 78.54

Conditional Compilationโ€‹

Useful when compiling different versions of code depending on system configurations or diagnostic requirements.

#include <stdio.h>

#define DEBUG_MODE 1

int main() {
#if DEBUG_MODE
printf("Debug output enabled\n");
#else
printf("Standard execution mode\n");
#endif
return 0;
}

// Output:
// Debug output enabled

๐Ÿ’พ File Handling Modes Cheatsheetโ€‹

In C, we interact with files using the FILE structure pointer.

#include <stdio.h>

int main() {
FILE *fp = fopen("output.txt", "w"); // Open file for writing

if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}

fprintf(fp, "VD Docs: File I/O Quick Reference"); // Write to file
fclose(fp); // Always close files to flush streams

printf("File written\n");
return 0;
}

// Output:
// File written

Standard File Operations Tableโ€‹

FunctionSyntaxDescription
fopen()FILE *fopen(const char *filename, const char *mode)Opens a file and returns a file pointer.
fclose()int fclose(FILE *stream)Closes an open file stream.
fgetc()int fgetc(FILE *stream)Reads a single character from stream.
fputc()int fputc(int char, FILE *stream)Writes a single character to stream.
fgets()char *fgets(char *str, int n, FILE *stream)Reads a line of characters until newline or end-of-file.
fputs()int fputs(const char *str, FILE *stream)Writes a string to stream.
fprintf()int fprintf(FILE *stream, const char *format, ...)Writes formatted text to stream.
fscanf()int fscanf(FILE *stream, const char *format, ...)Reads formatted data from stream.

Access Modes Checklistโ€‹

  • "r": Read Mode. File must exist. Starts reading from the beginning.
  • "w": Write Mode. Creates a new file if it doesn't exist. Overwrites existing contents.
  • "a": Append Mode. Creates file if it doesn't exist. Writes new data at the end.
  • "r+": Read + Write. File must exist. Starts at the beginning.
  • "w+": Read + Write (Overwrite). Creates or overwrites.
  • "a+": Read + Write (Append). Creates or appends.
  • Binary Suffix: Append b to any mode (e.g., "rb", "wb", "ab") for binary file operations.

๐Ÿ“Š Sample Dry Run: Swapping by Referenceโ€‹

Let's trace what happens in system memory when we call swapByReference(&x, &y) where x is stored at memory address 0x1000 (value 10) and y is stored at memory address 0x1004 (value 20).

StepInstructionPointer a (Address)Pointer b (Address)Variable tempValue at *a (Address 0x1000)Value at *b (Address 0x1004)Description
1int temp = *a;0x10000x1004101020Store the value at a (which is x) into temp โš™๏ธ
2*a = *b;0x10000x1004102020Copy the value at b into the memory of a โš™๏ธ
3*b = temp;0x10000x1004102010Copy the value of temp into the memory of b โš™๏ธ

๐Ÿ“š Best Practices & Common Mistakesโ€‹

โœ… Best Practicesโ€‹

  • Use sizeof for array bounds: Instead of hardcoding lengths, use sizeof(arr) / sizeof(arr[0]) to find the number of elements in an array.
  • Always close file pointers: Neglecting fclose(fp) keeps system file handles open, potentially lock-protecting or corrupting files.
  • Check for NULL on malloc: Memory allocation is not guaranteed to succeed on resource-constrained platforms. Always check if (ptr == NULL).

โŒ Common Mistakes โš ๏ธโ€‹

  • Missing semicolon on structures: Writing struct Point { int x; int y; } without the ending semicolon (;).
  • Using & with string variables in scanf: Declaring char name[20]; and calling scanf("%s", &name); instead of scanf("%s", name);. The array name decays into a pointer automatically.
  • Using = instead of == in conditionals: Writing if (x = 5) instead of if (x == 5). The former assigns 5 to x and evaluates to true.
  • Array index out of bounds: Declaring int arr[5] and accessing arr[5]. The last valid element is arr[4].

๐ŸŽฏ Practice Problemsโ€‹

Easy Level ๐ŸŸขโ€‹

  1. Write a program to print the sizes of all native types (char, int, float, double, pointers) on your local system using sizeof.
  2. Implement a macro C_TO_F(c) that converts Celsius to Fahrenheit and test it.

Medium Level ๐ŸŸกโ€‹

  1. Create a struct Book containing title, author, and price. Initialize it and write a helper function to print the details.
  2. Implement a function to find the maximum element in an array using pointers.

Hard Level ๐Ÿ”ดโ€‹

  1. Write a command-line utility in C to copy the contents of a text file to another file, while handling potential file-not-found errors.
  2. Dynamically allocate a 1D array of integers. Read inputs, double the array size using realloc() when the user enters more items, and print final outputs without memory leaks.

โ“ Frequently Asked Questionsโ€‹

Details

Q: What is the difference between #include <file.h> and #include "file.h"? Angle brackets <file.h> instruct the compiler to search the system header search paths (standard library folders). Double quotes "file.h" search the local project directory first, and fall back to system header directories if not found.

Details

Q: Why does scanf("%s", name) stop reading when it encounters a space? The %s format specifier treats whitespaces (spaces, tabs, newlines) as string delimiters. To read a line with spaces, use fgets(name, sizeof(name), stdin) instead.

Details

Q: What is a segmentation fault (segfault) and why does it occur? A segmentation fault is a runtime error that occurs when a program tries to access memory it does not have permission to access. Common causes include dereferencing a NULL pointer, accessing an array index out of bounds, or stack overflow from endless recursion.


โœ… Summaryโ€‹

In this cheatsheet, you have learned:

  • โœ… The minimum boilerplate skeleton required to compile and run any C program.
  • โœ… The core format specifiers and variable types used for input/output.
  • โœ… Conditional and loop control structures to direct program paths.
  • โœ… String helper functions and pointer dereferencing methods.
  • โœ… How memory layout differs between structures and unions, plus file modes.

๐Ÿ’ก Pro Tip: "The only way to learn a new programming language is by writing programs in it." - Dennis Ritchie, Creator of C.


๐Ÿ“š Further Readingโ€‹

Continue your learning path:

Go deeper:

๐Ÿ“ Visit Us

๐Ÿซ VD Computer Tuition Surat

VD Computer Tuition
๐Ÿ“ Address
2/66 Faram Street, Rustompura
Surat โ€“ 395002, Gujarat, India
๐Ÿ“ž Phone / WhatsApp
+91 84604 41384
๐ŸŒ Website

Computer Classes & Tuition โ€” Areas We Serve in Surat

Adajanโ€ขAlthanโ€ขAmroliโ€ขAthwaโ€ขAthwalinesโ€ขBhagalโ€ขBhatarโ€ขBhestanโ€ขCanal Roadโ€ขChowkโ€ขCitylightโ€ขDumasโ€ขGaurav Pathโ€ขGhod Dod Roadโ€ขHaziraโ€ขJahangirpuraโ€ขKamrejโ€ขKapodraโ€ขKatargamโ€ขLimbayatโ€ขMagdallaโ€ขMajura Gateโ€ขMota Varachhaโ€ขNanpuraโ€ขNew Citylightโ€ขOlpadโ€ขPalโ€ขPandesaraโ€ขParle Pointโ€ขPiplodโ€ขPunaโ€ขRanderโ€ขRing Roadโ€ขRustampuraโ€ขSachinโ€ขSalabatpuraโ€ขSarthanaโ€ขSosyo Circleโ€ขUdhnaโ€ขVarachhaโ€ขVed Roadโ€ขVesuโ€ขVIP Road
๐Ÿ“ž Call Sir๐Ÿ’ฌ WhatsApp Sir