zelhajou / C-cheat_sheet

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

C Programming Language Cheat Sheet

Table of Contents

  1. Introduction
  2. Hello, World!
  3. TOKEN
  4. Keywords
  5. Variables & Data Type
  6. Storage Classes
  7. Characters Set
  8. Operators
  9. Control Flow
  10. Header files
  11. Preprocessor directives
  12. Functions
  13. File Handling Functions
  14. Input & Output
  15. Pointers
  16. File Management
  17. Memory Management
  18. Process management
  19. Synchronization
  20. Thread Management
  21. Signal Handling
  22. Error Handlling
  23. Structures for Object-Like Behavior)

Introduction

Category Information
Name C Programming Language
Paradigm Imperative (procedural), structured
Designed by Dennis Ritchie
Developer Dennis Ritchie & Bell Labs (creators)
Standardization ANSI C, ISO C, C99, C11
First appeared 1972
Stable release C18 / June 2018
Typing discipline Static, weak, manifest, nominal
OS Cross-platform
Syntax Style C-like
File Extension .c (source code), .h (header files)
Compilation Compiled language
Flow of Program Source Code -> Preprocessor (e.g., #include) -> Compiler (e.g., gcc) -> Linker (Combines Object Files) -> Executable Program -> Run the Program
Uses
  • Operating systems like LINUX, UNIX.
  • CAD/ CAM Applications and Word processors.
  • Embedded systems like ATMs, printers.
  • RDBMS MySQL, Language Compilers and Interpreters, Print Spoolers, Loaders, Linkers, Assemblers, Text Editors, Automation tools, Network Drivers.
Advantages
  • Relatively simple language
  • Reliable (able to be trusted)
  • Easy to understand and supports a rich set of data types
  • Easy to use, write, modify, and debug, and quick to learn
  • Can be compiled on a variety of computer platforms
Key Features Simple, Machine Independent or Portable, Mid-level programming language, structured programming language, Rich Library, Memory Management, Fast Speed, Pointers, Recursion, Extensible, Robust, Highly portable
Major implementations K&R C, GCC, Clang, Intel C, C++Builder, Microsoft Visual C++, Watcom C
Dialects Cyclone, Unified Parallel C, Split-C, Cilk, C*
Influenced by B (BCPL, CPL), ALGOL 68, Assembly, PL/I, FORTRAN
Influenced AMPL, AWK, csh, C++, C--, C#, Objective-C, D, Go, Java, JavaScript, Julia, Limbo, LPC, Perl, PHP, Pike, Processing, Python, Ring, Rust, Seed7, Vala, Verilog (HDL), Nim
Development Environments

IDEs: Visual Studio, Code::Blocks.
Text Editors: Vim, Emacs.
Compilers: GCC (GNU Compiler Collection), Clang.
Debuggers: GDB (GNU Debugger).
Build Systems: Make and CMake.
Documentation: Doxygen
Version Control: git
Libraries:

  • Standard C Library: stdio.h, stdlib.h...
  • rnal Libraries: OpenGL, SQLite...
C / C++ categorize statements into:
  • Selection [if and switch]
  • Iteration [while, for, do-while]
  • Jump [break, continue, goto and return]
  • Label [case and default]
  • Expression [statements composed of a valid expression]
  • Block [blocks of code. Each block begins with { and ends with } and referred to a compound statements
/*
- Multi-line
- Comment.
*/

#include<stdio.h> // Include header files

int main() // main() function must be there
{
printf("Hello, World!\n"); // semicolon after each statement
return 0; // indicate that program ended successfuly
} // program enclosed by curly braces

TOKEN

  • Keywords
  • Strings
  • Operators
  • Constants
  • Identifiers
  • Special Characters
  • auto;		break;		case;		char;	const;		continue
    default;	do;		double;		else;	enum;		extern
    float;		for;		goto;		if;	int;		long
    register;	return;		short;		signed;	sizeof;		static
    struct;		switch;		typedef;	union;	unsigned;	void;
    volatile;	while

    Rules for writing variable names:

    • Keywords should not be used.
    • Special characters should not be used as variables
    • Representing the variable names in lowercase is a virtue programming practice.
    • There is no limit on the number of characters in a variable name

    Example:

    // Valid variables Invalid variables
    char ab = 'A';
    int total_mark;
    int gross_weight_2020;
    int area_of_sphere;
    
    total_mark = 50;
    // Invalid variables
    char 8ab;
    int total mark;
    int gross-weight-2020;
    int area_ _of_ _sphere;

    Primary

    int, char, float, double, void;
    
    // Data type modifiers: Signed - unsigned - short - long
    signed int, unsigned int, short, long, long long;
    bool;

    Derived

    Function, Array, Pointer, String

    User-Defined

    struct, union, enum, typedef;

    Others

    size_t, pid_t, uid_t, gid_t, FILE, DIR, struct timeval, struct tm, struct stat, struct sockaddr, struct sockaddr_in, pthread_t, pthread_mutex_t,

    Type Conversion

    Implicit Type Conversion:

    bool -> char -> short int -> int -> unsigned int -> long -> unsigned long -> long long -> float -> double -> long double

    Explicit Type Conversion:

    (type) expression

    Macros

    NULL, EOF, stdin, stdout, stderr

    Constants

    O_RDONLY, O_WRONLY, O_RDWR, O_CREAT, O_APPEND, O_TRUNC, S_IRWXU, S_IRUSR, S_IWUSR, S_IXUSR, S_IRWXG, S_IRGRP, S_IWGRP, S_IXGRP, S_IRWXO, S_IROTH, S_IWOTH, S_IXOTH
    auto //Automatic storage duration. Default for local variables.
    register //Similar to auto, but suggests to the compiler to store the variable in a register for faster access.
    static // Preserves the value of the variable between function calls and has a file scope if declared outside functions.
    extern //Declares a variable or function that is defined in another file.

    Characters Set

    Alphabets: Upper case, Lower case

    Digits: [0−9]

    Special characters:~, !, #, $, %, ^, &, *, (, ), _, +, |, \, `, -, =, {, }, [, ], :, ", ;, <, >, ?, ,, ., /

    White spaces: Blank space, New line, Carriage return, Horizontal tab

    ASCII Table

    Unary: +, -, ++, --, !, &, *, ~, sizeof

    Binary:

    • Arithmetic operators: +, -, *, /, %
    • Comparison Operators: ==, !=, <, >, <=, >=
    • Logical operators: && || !
    • Assignment Operators: =, +=, -=, *=, /=, %=
    • Bitwise Operators: &, |, ^(XOR), ~(complement), <<(left shift), >>(right shift)

    Ternary: condition ? value_if_true : value_if_false

    Other Operators:

    Conditional statements: If-else Switch
    Loops: for while do-while Break Continue goto

    • If pre-test is required, use while or for loop.
    • If post-test is required, use do-while loop.
    • If the number of iterations is known, use for loop.
    • If the number of iterations is unknown, use while or do-while loop.
    • If the loop body should be executed at least once, use do-while loop.

    Header files

    stdio.h stdlib.h string.h math.h time.h ctype.h stdarg.h stddef.h stdbool.h limits.h float.h errno.h assert.h signal.h ctype.h locale.h setjmp.h

    #include
    #define
    #undef
    #ifdef / #ifndef
    #if / #elif / #else / #endif
    #line
    #error
    #pragma
    abs(x);			sqrt(x);	pow(x, y);	sin(x);
    cos(x);			tan(x);		log(x);		ceil(x);
    floor(x);		round(x);	fmod(x, y);	fabs(x);
    asin(x);		atan(x);	cosh(x);	sinh(x);
    tanh(x);		exp(x);		log10(x);	cbrt(x);
    hypot(x, y);		fmin(x, y);	fmax(x, y);	isnan(x);
    isinf(x);
    atof();		atoi();		atol();		ecvt();
    fcvt();		gcvt(); 	itoa();		ltoa();
    strtod();	strtol();	strtoul();	ultoa();
    isalnum();	isalpha();	isdigit();	islower();	isupper();	isspace();
    ispunct();	isxdigit();	isprint();	isgraph();	iscntrl();	tolower();	toupper();
    strlen();	strcpy();	strncpy();	strcat();	strncat();
    strcmp();	strncmp();	strchr();	strrchr();	strstr();
    strtok();	strspn();	strcspn();	memcpy();	memmove();
    memset();	

    Time Library Functions

    time();  localtime();  asctime();  strftime();

    Random Number Generation Library Functions

    rand();  srand();

    Input & Output

    Standard I/O (stdio.h)

    Formatted:

    • Input: scanf(), fscanf()
    • Output: printf(), fprintf()

    Unformatted:

    • Input: getchar() gets()
    • Output: putchar() puts()

    Format Specifiers:

    • %d - Integer
    • %ld - Long Integer
    • %lld - Long Long Integer
    • %u - Unsigned Integer
    • %lu - Unsigned Long Integer
    • %llu - Unsigned Long Long Integer
    • %f - Float
    • %lf - Double
    • %e, %E - Exponential Notation
    • %c - Character
    • %s - String
    • %p - Pointer
    • %x, %X - Hexadecimal (Lowercase, Uppercase)
    • %o - Octal
    • %g, %G - Float in Shortest Form
    • %% - Percentage

    Escape Sequences:

    • \n: Represents a newline character.
    • \t: Represents a tab character.
    • \r: Represents a carriage return character.
    • \\: Represents a backslash character.
    • \': Represents a single quote character.
    • \": Represents a double quote character.
    • \?: Represents a question mark character.
    • \a: Represents an alert (bell) character.
    • \b: Represents a backspace character.
    • \f: Represents a form feed character.
    • \v: Represents a vertical tab character.
    • \0: Represents a null character.

    File Descriptors

    • stdin (0)
    • stdout (1)
    • stderr (2)

    Low-level I/O

    open(); // Opens a file and returns a file descriptor.
    read(); // Reads data from an open file into a buffer.
    writ(); // Writes data from a buffer to an open file.
    close(); // Closes an open file.
    lseek(); // Moves the file pointer associated with an open file.
    unlink(); // Removes a file from the file system.

    Buffered I/O

    fopen(); //Opens a file for reading or writing
    fclose(); // Closes the specified file stream
    fflush(); // Flushes the output buffer of a stream
    setvbuf(); // Sets the buffering mode and size for the specified stream
    fprintf(); // Writes formatted data to the specified stream
    fscanf(); // Reads formatted data from the specified stream
    fread(); // Reads data from a stream into the specified buffer
    fwrite(); // Writes data from the specified buffer to a stream

    Terminal I/O Library Functions

    printf(); scanf(); getchar(); putchar(); getch(); getche(); 

    Types of Pointers: NULL Pointers, Void Pointers, Function Pointers, Array Pointers, Double Pointe

    Pointer Operations: Declaration and Initialization, Dereferencing, Pointer Arithmetic, Pointer Comparison, Casting Pointer

    Common Pointer Usages: Dynamic Memory Allocation, Passing by Reference, Array Manipulation, Data Structures (Linked Lists), Callback Functions, Pointers to Functions, File Handling (File Pointers), Pointer to Structures, String Manipulation

    Pointer Pitfalls: Null Pointer Dereferencing, Dangling Pointers, Memory Leaks, Uninitialized Pointers, Pointer Arithmetic Error

    File Opening and Closing:

    fopen(); // Open a file.
    fclose(); // Close a file.

    Reading and Writing Data:

    fread(); // Read data from a file.
    fwrite(); // Write data to a file.

    File Positioning:

    fseek(); // Move the file pointer to a specified position.
    ftell(); // Get the current position of the file pointer.
    rewind(); // Move the file pointer to the beginning of the file.

    Directory Operations:

    opendir(); // Open a directory stream for reading.
    readdir(); // Read a directory entry.
    closedir(); // Close a directory stream.
    getcwd(); // Get the current working directory.

    File and Directory Manipulation:

    mkdir(); // Create a new directory.
    rmdir(); // Remove a directory.
    chdir(); // Change the current working directory.
    remove(); // Delete a file.
    rename(); // Rename a file or directory.
    link(); // Create a link to a file.
    unlink(); // Remove a link to a file.
    stat(); // Get file status.

    File Permission Functions:

    chmod(); Change file permissions.
    access(); Check file accessibility.

    Memory Management

    Memory Allocation:

    • Static Allocation: Memory is allocated at compile-time
    • Dynamic Allocation: Memory is allocated at runtime
    • Memory Layout: Text Segment, Data Segment, Heap, Stack, Memory Mapping (MMap), Environment Variables and Command Line Arguments

    Dynamic Memory Allocation:

    malloc();	// Allocate memory dynamically
    calloc();	// Allocate contiguous block of memory and initializes it to zero
    realloc();	// Reallocate memory dynamically
    
    // Memory Leaks Tool: Valgrind

    Memory Deallocation:

    free(); // Deallocate memory

    Memory Management:

    brk(); //Set the end of the data segment to the specified value.
    mmap(); //Map files or devices into memory.
    munmap(); //Unmap files or devices from memory.

    Process management

    Process States

    • Running
    • Ready
    • Blocked (or Waiting)
    • Terminated

    Process Control Block (PCB)

    • Process ID (PID)
    • Program counter and CPU registers
    • Memory allocation details
    • Process state
    • Priority and scheduling information
    • Open file descriptors
    • Parent and child process information
    fork(); // Create a new process by duplicating the existing process.
    exec(); // Replace the current process with a new one.
    wait(); // Wait for a child process to terminate.
    exit(); // Terminate the current process.
    
    // Information Maintenance
    getpid(); // Get the process ID of the current process.
    getppid(); // Get the parent process ID.
    getuid(); // Get the user ID of the current process.
    getgid(); // Get the group ID of the current process.
    uname(); // Get system information including the operating system name, version, and more

    Synchronization

    mutex
    semaphore
    condition variable

    Thread Management

    pthread_create(); // Used to start a new thread in the calling process
    pthread_join(); // Waits for the thread specified by thread to terminate
    pthread_exit(); // Terminates the calling thread.
    
    // Synchronization
    pthread_mutex_init()
    pthread_mutex_destroy()
    pthread_mutex_lock()
    pthread_mutex_unlock()

    Signal Handling

    Standard Signals

    • Termination Signals: SIGABRT, SIGTERM
    • Interrupt Signals: SIGINT, SIGQUIT
    • Fault Signals: SIGILL, SIGFPE, SIGSEGV
    • Alarm Signals: SIGALRM, SIGVTALRM
    • I/O Signals: SIGPIPE, SIGPOLL
    • Miscellaneous Signals: SIGHUP, SIGBUS, SIGCHLD, SIGCONT, SIGSTOP, SIGTSTP, SIGTTIN, SIGTTOU, SIGUSR1, SIGUSR2, SIGPROF, SIGSYS, SIGTRAP, SIGURG, SIGXCPU, SIGXFSZ

    Real-time Signals

    • Real-time Signals: SIGRTMIN to SIGRTMAX

    Signal Functions

    Signal Handling:

    signal(); // Establishes a signal handler for a specific signal.
    sigaction(); // Examines and changes the action associated with a specific signal.

    Signal Sending:

    raise(); // Sends a signal to the calling process.
    kill(); // Sends a signal to a specified process or process group.

    Signal Set Manipulation:

    sigemptyset(); // Initializes an empty signal set.
    sigfillset(); // Initializes a signal set to contain all signals.
    sigaddset(); // Adds a specified signal to a signal set.
    sigdelset(); // Removes a specified signal from a signal set.
    sigismember(); // Checks if a specified signal is a member of a signal set.

    Signal Masking:

    sigprocmask(); // Examines and changes the calling process's signal mask.
    perror();
    strerror();

    Structures for Object-Like Behavior

    • In C, there are no built-in classes and objects as in object-oriented languages, but you can achieve similar functionality using structures.
    • Structures allow you to group different data types together into a single unit.
    • You can use structures to create custom data types that resemble objects.
    #include <stdio.h>
    #include <string.h>
    
    // Define a structure
    struct Person {
        char name[50];
        int age;
    };
    
    int main() {
        // Create an instance of the structure
        struct Person person1;
        strcpy(person1.name, "John");
        person1.age = 30;
    
        // Access and manipulate data within the structure
        printf("C: %s is %d years old.\n", person1.name, person1.age);
    
        return 0;
    }