This C language cheat sheet provides a quick reference guide to the essential syntax, operators, control flow, functions, data structures, and standard library functions in C. Perfect for both beginners and experienced programmers, it covers everything from basic syntax and operators to advanced topics like dynamic memory allocation and file I/O. Keep this handy for efficient coding and problem-solving in C.
Basic Syntax and Structure
Hello World Program
#include <stdio.h>
int main() {
printf("Hello, World!");
return 0;
}
Basic Structure of a C Program
- Include Headers
- Define Constants and Macros
- Declare Functions
- Main Function
- Other Functions
Comments
// Single-line comment
/*
Multi-line comment
*/
Data Types and Variables
Primitive Data Types
- int
- char
- float
- double
Variable Declaration and Initialization
int a = 10;
char b = 'c';
float c = 3.14;
double d = 3.14159;
Constants
#define PI 3.14
const int a = 10;
Operators
Arithmetic Operators
+
Addition:a + b
-
Subtraction:a - b
*
Multiplication:a * b
/
Division:a / b
%
Modulus:a % b
++
Increment:a++
--
Decrement:a--
Relational Operators
==
Equal to:a == b
!=
Not equal to:a != b
>
Greater than:a > b
<
Less than:a < b
>=
Greater than or equal to:a >= b
<=
Less than or equal to:a <= b
Logical Operators
&&
Logical AND:a && b
||
Logical OR:a || b
!
Logical NOT:!a
Bitwise Operators
&
AND:a & b
|
OR:a | b
^
XOR:a ^ b
~
NOT:~a
<<
Left shift:a << 2
>>
Right shift:a >> 2
Assignment Operators
=
Assign:a = b
+=
Add and assign:a += b
-=
Subtract and assign:a -= b
*=
Multiply and assign:a *= b
/=
Divide and assign:a /= b
%=
Modulus and assign:a %= b
&=
AND and assign:a &= b
|=
OR and assign:a |= b
^=
XOR and assign:a ^= b
<<=
Left shift and assign:a <<= b
>>=
Right shift and assign:a >>= b
Miscellaneous Operators
sizeof
Size of:sizeof(a)
? :
Ternary:(a > b) ? a : b
Examples
int a = 10, b = 5, result;
result = a + b; // Addition
result = a - b; // Subtraction
result = a * b; // Multiplication
result = a / b; // Division
result = a % b; // Modulus
result = a & b; // Bitwise AND
result = a | b; // Bitwise OR
result = a ^ b; // Bitwise XOR
result = ~a; // Bitwise NOT
result = a << 1; // Left shift
result = a >> 1; // Right shift
a += b; // Addition assignment
b -= a; // Subtraction assignment
result = (a > b) ? a : b; // Ternary operator
Control Flow
Conditional Statements
if (condition) {
// code
} else {
// code
}
switch (expression) {
case constant1:
// code
break;
case constant2:
// code
break;
default:
// code
}
Loops
for (initialization; condition; increment) {
// code
}
while (condition) {
// code
}
do {
// code
} while (condition);
Break and Continue
break;
continue;
Goto Statement
goto label;
label: // code
Functions
Function Declaration and Definition
returnType functionName(parameter1, parameter2, ...) {
// code
return value;
}
Function Call
functionName(arg1, arg2, ...);
Return Statement
return value;
Parameter Passing
- By value
- By reference
Recursion
int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}
Arrays and Strings
One-dimensional Arrays
int arr[10];
Multidimensional Arrays
int arr[3][4];
String Handling Functions
strcpy(destination, source);
strcat(destination, source);
strlen(string);
Array of Strings
char *arr[] = {"string1", "string2"};
Pointers
Pointer Basics
int *ptr;
Pointer Arithmetic
ptr++
ptr--
ptr+5
ptr-5
Pointers and Arrays
int arr[5];
int *ptr = arr;
Pointers to Pointers
int **ptr;
Function Pointers
void (*funcPtr)(int, int);
Structures and Unions
Defining Structures
struct StructureName {
type member1;
type member2;
// ...
};
Accessing Structure Members
struct StructureName s;
s.member1 = value;
Structure Arrays
struct StructureName arr[10];
Nested Structures
struct Outer {
struct Inner {
// ...
} inner;
};
Unions
union UnionName {
type member1;
type member2;
// ...
};
Dynamic Memory Allocation
malloc(), calloc(), realloc(), free()
ptr = malloc(size);
ptr = calloc(num, size);
ptr = realloc(ptr, newSize);
free(ptr);
Memory Leaks and Management
- Always free allocated memory
File I/O
File Handling Functions
FILE *fptr;
fptr = fopen("filename", "mode");
fclose(fptr);
fread(buffer, size, count, fptr);
fwrite(buffer, size, count, fptr);
File Modes
"r"
"w"
"a"
"r+"
"w+"
"a+"
Reading and Writing Files
fscanf(fptr, "format", &variable);
fprintf(fptr, "format", variable);
Preprocessors and Macros
define and #undef
#define NAME value
#undef NAME
include
#include <header.h>
#include "file.h"
Conditional Compilation
#ifdef MACRO
// code
#endif
#ifndef MACRO
// code
#endif
#if condition
// code
#elif condition
// code
#else
// code
#endif
Macros with Arguments
#define MACRO(arg1, arg2) (arg1 + arg2)
Standard Library Functions
stdio.h
printf
- formatted output to stdoutscanf
- formatted input from stdinfprintf
- formatted output to a filefscanf
- formatted input from a filesprintf
- formatted output to a stringsscanf
- formatted input from a stringfopen
- open a filefclose
- close a filefgets
- read a string from a filefputs
- write a string to a filefgetc
- get a character from a filefputc
- write a character to a filefeof
- check for end-of-fileferror
- check for file error
stdlib.h
malloc
- allocate memorycalloc
- allocate and zero-initialize memoryrealloc
- reallocate memoryfree
- free allocated memoryatoi
- convert string to integeratof
- convert string to floatatol
- convert string to longabs
- compute absolute valuerand
- generate random numbersrand
- seed the random number generatorqsort
- quick sortbsearch
- binary searchexit
- terminate the programsystem
- execute a system command
string.h
strlen
- get string lengthstrcmp
- compare two stringsstrncmp
- compare a portion of two stringsstrcpy
- copy a stringstrncpy
- copy a portion of a stringstrcat
- concatenate two stringsstrncat
- concatenate a portion of a stringstrstr
- locate a substringstrchr
- locate the first occurrence of a characterstrrchr
- locate the last occurrence of a characterstrtok
- tokenize a stringstrdup
- duplicate a stringmemcpy
- copy memory areamemmove
- move memory areamemset
- fill memory with a constant bytememcmp
- compare two memory areas
math.h
sqrt
- compute square rootpow
- compute powerexp
- compute exponentiallog
- compute natural logarithmlog10
- compute common logarithmsin
- compute sinecos
- compute cosinetan
- compute tangentasin
- compute arc sineacos
- compute arc cosineatan
- compute arc tangentatan2
- compute arc tangent with two argumentsceil
- compute ceilingfloor
- compute floorfabs
- compute absolute value of a floating-point number
time.h
time
- get current timeclock
- get processor timedifftime
- compute difference between two timesmktime
- convert broken-down time to calendar timeasctime
- convert time to a stringctime
- convert time to a stringgmtime
- convert time to Coordinated Universal Time (UTC)localtime
- convert time to local timestrftime
- format time as a string
Miscellaneous
Command Line Arguments
int main(int argc, char *argv[]) {
// code
}
Inline Functions
inline returnType functionName(parameters) {
// code
}
Volatile Keyword
volatile int var;
Typedef
typedef existingType newTypeName;
Best Practices and Tips
Code Readability
- Indentation: Use consistent indentation to make code more readable.
- Naming Conventions: Use meaningful variable and function names. Follow conventions like camelCase for variables and PascalCase for functions.
- Spacing: Use spaces around operators and after commas for better readability.
Commenting and Documentation
- Single-line Comments: Use
//
for brief comments. - Multi-line Comments: Use
/* */
for detailed explanations. - Function Comments: Describe the purpose, parameters, and return value of functions.
- Inline Comments: Explain complex logic within the code.
Debugging Tips
- Use a Debugger: Utilize tools like gdb to step through your code and inspect variables.
- Print Statements: Use
printf
to print variable values and checkpoints in the code. - Check Compiler Warnings: Always compile with
-Wall
to enable all warnings and fix them.
Optimization Techniques
- Avoid Unnecessary Calculations: Store repeated calculations in a variable.
- Efficient Algorithms: Choose appropriate algorithms and data structures for the task.
- Memory Management: Free dynamically allocated memory to avoid leaks.