- Introduction
- Hello, World!
- TOKEN
- Keywords
- Variables & Data Type
- Storage Classes
- Characters Set
- Operators
- Control Flow
- Header files
- Preprocessor directives
- Functions
- File Handling Functions
- Input & Output
- Pointers
- File Management
- Memory Management
- Process management
- Synchronization
- Thread Management
- Signal Handling
- Error Handlling
- Structures for Object-Like Behavior)
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 |
|
|
Advantages |
|
|
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.
|
|
C / C++ categorize statements into: |
|
/*
- 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
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
- 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;
int, char, float, double, void;
// Data type modifiers: Signed - unsigned - short - long
signed int, unsigned int, short, long, long long;
bool;
Function, Array, Pointer, String
struct, union, enum, typedef;
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,
Implicit Type Conversion:
bool -> char -> short int -> int -> unsigned int -> long -> unsigned long -> long long -> float -> double -> long double
Explicit Type Conversion:
(type) expression
NULL, EOF, stdin, stdout, stderr
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.
Alphabets: Upper case, Lower case
Digits: [0−9]
Special characters:~
, !
, #
, $
, %
, ^
, &
, *
, (
, )
, _
, +
, |
, \
, `
, -
, =
, {
, }
, [
, ]
, :
, "
, ;
, <
, >
, ?
, ,
, .
, /
White spaces: Blank space, New line, Carriage return, Horizontal tab
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:
- sizeof:
sizeof()
- Comma:
( , )
- dot (.) and arrow (->):
.
,->
- Cast Operator
- &,* Operator: Pointer operator & returns the address of a variable
Conditional statements: If-else
Switch
Loops: for
while
do-while
Break
Continue
goto
- If pre-test is required, use
while
orfor
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
ordo-while
loop. - If the loop body should be executed at least once, use
do-while
loop.
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(); localtime(); asctime(); strftime();
rand(); srand();
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
fopen(); // Open a file.
fclose(); // Close a file.
fread(); // Read data from a file.
fwrite(); // Write data to a file.
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.
opendir(); // Open a directory stream for reading.
readdir(); // Read a directory entry.
closedir(); // Close a directory stream.
getcwd(); // Get the current working directory.
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.
chmod(); Change file permissions.
access(); Check file accessibility.
- 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
malloc(); // Allocate memory dynamically
calloc(); // Allocate contiguous block of memory and initializes it to zero
realloc(); // Reallocate memory dynamically
// Memory Leaks Tool: Valgrind
free(); // Deallocate memory
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.
- Running
- Ready
- Blocked (or Waiting)
- Terminated
- 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
mutex
semaphore
condition variable
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()
- 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:
SIGRTMIN
toSIGRTMAX
signal(); // Establishes a signal handler for a specific signal.
sigaction(); // Examines and changes the action associated with a specific signal.
raise(); // Sends a signal to the calling process.
kill(); // Sends a signal to a specified process or process group.
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.
sigprocmask(); // Examines and changes the calling process's signal mask.
perror();
strerror();
- 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;
}