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).
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:
- Preprocessing: Processes directives (lines starting with
#), expands macros, and includes headers. - Compilation: Translates the preprocessed file into assembly language.
- Assembly: Translates assembly code into machine-readable object code (
.oor.objfile). - 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 Type | Typical Size (64-bit GCC) | Range (Approx.) | Format Specifier | Example Declaration |
|---|---|---|---|---|
char | 1 Byte | -128 to 127 | %c | char letter = 'A'; |
int | 4 Bytes | -2 x 10โน to 2 x 10โน | %d or %i | int count = 105; |
unsigned int | 4 Bytes | 0 to 4 x 10โน | %u | unsigned int age = 18; |
short int | 2 Bytes | -32,768 to 32,767 | %hd | short int temp = -5; |
long int | 8 Bytes | -9 x 10ยนโธ to 9 x 10ยนโธ | %ld | long int dist = 987654321L; |
float | 4 Bytes | 6 decimal places | %f or %g | float price = 99.99f; |
double | 8 Bytes | 15 decimal places | %lf | double pi = 3.14159265359; |
String (Char Array) | 1 Byte per char | N/A | %s | char name[] = "Surat"; |
Pointer Address | 8 Bytes | Memory address | %p | int *ptr = &count; |
size_t | 8 Bytes | 0 to max size | %zu | size_t len = sizeof(int); |
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!
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 Function | Syntax | Description |
|---|---|---|
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
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.
| Function | Signature | Description |
|---|---|---|
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โ
| Feature | Structure (struct) | Union (union) |
|---|---|---|
| Memory Allocation | Allocates distinct memory addresses for every member. | Allocates a single shared memory block matching the largest member. |
| Size | Sum of sizes of all members (plus padding). | Equal to the size of the largest member. |
| Member Access | You 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โ
| Function | Syntax | Description |
|---|---|---|
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
bto 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).
| Step | Instruction | Pointer a (Address) | Pointer b (Address) | Variable temp | Value at *a (Address 0x1000) | Value at *b (Address 0x1004) | Description |
|---|---|---|---|---|---|---|---|
| 1 | int temp = *a; | 0x1000 | 0x1004 | 10 | 10 | 20 | Store the value at a (which is x) into temp โ๏ธ |
| 2 | *a = *b; | 0x1000 | 0x1004 | 10 | 20 | 20 | Copy the value at b into the memory of a โ๏ธ |
| 3 | *b = temp; | 0x1000 | 0x1004 | 10 | 20 | 10 | Copy the value of temp into the memory of b โ๏ธ |
๐ Best Practices & Common Mistakesโ
โ Best Practicesโ
- Use
sizeoffor array bounds: Instead of hardcoding lengths, usesizeof(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
NULLon malloc: Memory allocation is not guaranteed to succeed on resource-constrained platforms. Always checkif (ptr == NULL).
โ Common Mistakes โ ๏ธโ
- Missing semicolon on structures: Writing
struct Point { int x; int y; }without the ending semicolon (;). - Using
&with string variables inscanf: Declaringchar name[20];and callingscanf("%s", &name);instead ofscanf("%s", name);. The array name decays into a pointer automatically. - Using
=instead of==in conditionals: Writingif (x = 5)instead ofif (x == 5). The former assigns5toxand evaluates to true. - Array index out of bounds: Declaring
int arr[5]and accessingarr[5]. The last valid element isarr[4].
๐ฏ Practice Problemsโ
Easy Level ๐ขโ
- Write a program to print the sizes of all native types (char, int, float, double, pointers) on your local system using
sizeof. - Implement a macro
C_TO_F(c)that converts Celsius to Fahrenheit and test it.
Medium Level ๐กโ
- Create a
struct Bookcontaining title, author, and price. Initialize it and write a helper function to print the details. - Implement a function to find the maximum element in an array using pointers.
Hard Level ๐ดโ
- 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.
- 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 aNULL 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: