C is a mid-level programming language providing low-level memory access (manual memory
management)
Developed by Dennis Ritchie of bell labs
Its procedural: focuses on data, processes and actions (tells what to do and how to do step by step
instructions)
#include <stdio.h> ->Header file
int main(void) -> main function
// This prints "Hello World"
printf("Hello World");
return 0;
A header file is a file with an extension of .h which contains C function declarations and macro
definitions. Lines starting with # are pre-processor directives which are processed by a pre-processor
before compilation. Its basically file inclusion and text replacement.
Main does not take an argument but sometimes we pass void because in older versions empty
meant that any number of arguments could be passes but in newer versions that’s not a problem
The value returned by the main indicates the status of
program termination. Return 0 indicates successful terminates
and passes control back to os.
Comments are added for documentation and ignored by compiler (//)
/* */ for multiline comment
In C a statement is always terminated by a semicolon
C does not support oop but cpp does
gcc filename.c –o filename
we use -o to define output file name. if we don’t use this it automatically is [Link]
./[Link] executes the programme
1. Pre-processing (involves expansion of macros, stripping of comments and expansion of
included files)-> produces filename. I
2. Compiling->filename.s compiles to assembly language and gives to assembler
3. Assembler converts to machine instructions->filename.o (functions with definitions missing
are resolved at linking phase)
4. Linking (adds extra code that is needed for program start and end) it links multiple object
files and libraries into a single executable. Resolves functions using libraries
Static linking-all library code is copied into executable
Dynamic linking-only name are referred to in code and refereed during runtime (gcc by
default provided dynamic link)
Identifiers- names for program elements or variables, functions, arrays etc
Set of rules for naming an identifier
The community has some naming conventions like for variables use camelCase start with lowercase,
constants use CAPITAL, functions use camelCase as well and are usually verbs describing the actions,
and structures usually nouns.
Keyword are words reserved by C for specific purposes and can’t be modified but identifier is user
defined and can be modified
Storage classes define the lifetime a scope of variables
Auto-can be accessed only inside the function/block in which
they are defined-default storage class for local variables. Not
used in front of func because they are not limited to block
scope
Static- preserve their value even after out of scope (preserve
value of last use in scope)
Register- suggests storing variable in register for faster access
but compiler may ignore/accept based on availability
Extern-tells that it’s defined in different block but can be
overwritten in different block as well.
There are 32 reserved keyword in c
Variable- to create this we have to specify name and data type. Every variable must be declared
before usage. The first value stored is called initial value and this is called iniatlization using =
Its important because until then only a garbage value was stored
You cant declare and use the variable in the same line
Variable act as name for memory location storing some value
Memory is not allocated at declaration its allocated at definition
Size of memory assigned depends on type of variable (can be found out using sizeof())
Global variables are declared in global scope and are visible in every part of the program also called
file scope (extern make it accessible to other files (linkage) ,static to current file only)
Local variables in local scope and accessible inside block have no linkage
Const checks data type, used for immutable variabels whereas define is text replacement and no
data type checking involved
Constants can also be refereed to as literals(they are constant values assigned to variables)
Multicharacter variables cant be defined by name of single char
Char star=’**’ is not valid
Int- size of 4 bytes (%d)
Data type modifiers (used to modify sign length or range of og keyword)
-short (converts int to two bytes) only with int
-long(for int and double)-doubles the size
-unsigned (shifts data range to positive part of whole numbers)
-signed(default data modifier for int and char)
Char-stores a single character-1 byte(%c)
Float- size of 4 bytes-%f
Double-more precision than float size of 8 bytes-%lf
Void=represents empty or no value
Type conversion-implicit and explicit. Implicit is done automatically by the compiler (like in
arithmetic operations to make them compatible and helps prevent data loss)
Implicit conversion from small data type to big datatype is not possible but vice versa is possible
because chote memory me you cant put a larger memory but you can do it vice versa
Explicit is done by programmer manually using typecast operator (type)
Basic I/O in C
Printf() is for printing formatted output to the standard output which is generally the
console screen.
Escape sequences are special characters that cannot be directly entered or carry a specific
control function. (\n for newline)
Fputs() used to output strings to files but can be made to console using stdout
Fputs(“hi”,stdout);
Scanf() is for reading user input. The arguments takes formatted string and address of the
variable where its to be stored.
It cannot handle whitespaces and stops at the first space. To handle this we have fgets()
Fgets(name,sizeof(name),stdin)
For reading a single character we use getchar()
Getchar and putchar both return int
Printf(%d, putchar(ch)) writes the char as well as ascii of character
If there is another functions inside printf see what it returns. Printf return the nymber of
characters it printed
Scanf returns the number of inputs successfully read
We use %% to print % in printf
++a increment first and then use value
A++ use value and then increment
\r takes cursor back to start of line
Operators
Of three types- unary, binary and ternary based on the number of operands they work on
Operator precedence is important division modulus are more than + and – and they are
more than bitwise shift but all are left to right associative.
The conditional operator is the only ternary operator in c
Exp1?exp2:exp3
Exp1 is condition to be evaluated: if true then execute exp2 otherwise exp3
Dot and arrow are used to reference members of classes, structures etc.
Modulo operator only works on integers and give integer output
Address operator (&) returns the address and deference operator(*) is pointer to variable
(can be used to get data stored at that address)
Conditional
in the if else ladder, the if statements are executed from top down if any is fulfilled the
further is bypassed. Its like the switch statement (should evaluate to only int or char)
unconditional jumps
break->terminated the loop
continue->skips the iteration and moves to next
goto->unconditional jump
return->passes control back to calling function
Looping
For (iniatilisation;condition;updation)
For (;;) is infinite loop
In while initialistaion and updation is done manually
Do while will execute once atleast irrespective of test condition
Functions
Functions are blocks of code that allow you to write a piece of logic once and
reuse it later on when needed
Function syntax-
Return_type function_name (parameter list) {
}
Function names follows same rules of naming as variable
Parameter list is the set of input values passed to the function.
Function declaration and definition are different- declaration involves telling compiler about
functions name and return type and parameters before its actually used and doesn’t contain
function body. Declaration is also called function prototype
Definition involves the actual implementation and logic of function.
Declaration is needed when a function is defined after a function that uses it. That involves
the compiler to recognise function and check for correct usage.
There are two main types of functions in C:
Library function- these are built in function in C such as printf(), scanf(), you can use them by
using appropriate header file like #include<stdio.h> or #include<math.h>
User defined function- these are functions created by the user and can be of main four
types:
1. No arguments no return value
2. Arguments no return value
3. No arguments return value
4. Arguments and return value
There are two ways to pass arguments to user defined function:
Call by value and call by reference (call by pointers). In call by value copies of the value is
passed to function and changes made in function are not reflected back to same value. But
in call by ref. address of arguments is passed to function and changes are reflected back. We
can use pointers in arguments to receive the addresses.
When a function is called memory for its variables and other data is allocated in a separated
block in a stack called stack frame. The stack in which its created is called function call stack.
When the function completes it execution the stack frame is deleted from stack, freeing up
memory and passing control back to calling function. The stack pointer points to top of call
stack.
Formal parameters are placeholders used in function declaration/definition.
While actual parameters are actual expressions or values passed during function call->also
called arguments.
Main function
entry point of C program. It’s a user defined function where execution of proram starts.
Its return value tells us if program was successful or not.
Void return type is supported but generally noy recommended as the os does not get
notification of execution if no value is returned.
Main function can be written with command line arguments or without.
As main function is called by os the user has to provide arguments at time of starting
program from command line hence called command line arguments.
Int argc= integer variable storing the number of command line arguments passed including
the name of the programme
Char *argv[]=array of character pointers listing all arguments argv[0] is name of programme.
First second third- three arguments
“first second third” or ‘first second third’=1 argument
Recursion
It’s a technique in which a function is called again and again until a specific base condition is
met.
Study
Compound data types
Arrays
Linear data structure that stores a fixed size sequence of elements of same data type in
contiguous memory locations.
Allows random access which is enabled by continuous memory storage. (address of first
element and index number). The name of the array is itself pointer to first element of the
[Link] arr pointer is a constan pointer and does not support increment operation (non-
modifiable)
In c arrays have fixed memory size and should be known at compile time.
Cannot store elements of different data type
Indexing starts with 0 and ends at (size-1)
Contiguous or consecutive memory locations are used. In multidimensional arrays as well
row major order (row after row) or column major order (column after column) can be used,
In c array bound checking is not found hence on accessing an element out of array bounds
will not throw an error but instead a garbage value.
Array decay- when array is passed as pointer then dimensions are lost and size tells size of
pointer to first element of the array. Func(int *arr)c does not pass entire array to function..it
passes the pointer to first element.
Declaration of array- type name size
Upon declaration the array elements store garbage values before initialisation. Skip
mentioning size of array If declaration and initialisation happen at same time. You can also
partially declare in this case the remaining elements are given 0
Size of array can be given as sizeof (arr)/sizeof(arr[0])
In functions arrays are always passed as pointers causing array decay. (size info is lost)
A subarray is sequence of elements that appear consecutively and same sequence as
original array.
Multidimensional arrays
The general method of declaring multidimensional arrays is type name [size1][size2]….
[sizen]
Size1*size2…*sizen=gives total elements that can be stored
If you perform both declaration and iniatilsation at same time in 2d array you may not
define number of rows but no of columns is compulsory.
Pointers and array
For accessing element of 2d array use *(*(arr+i) +j)
Arr+I gives address of ith row of arr and to address a pecific element we use +
For accessing 3d array use *(*(*(arr+i)+j)+k)
Pointers
a pointer is a variable storing memory address of another variable.
Backbone of low level memory manipulation in C
Declared as data_type *name
Data type indicates the type of variable that pointer is pointing to
Accesing the pointer directly gives us the address of the element stored. To get value we use
dereferencing operator (*)
Iniatilise pointer by equting to address of variable using address operator.
C provides format specifier %p for printing pointers.
Types of pointers
Null pointer-pointer that do not point to any memory location
Void pointer- no associated data type also called generic pointers as can by casted into any
type.