C Language Theory
C Language Theory
C Language Theory
C LANGUAGE
HISTORY OF C
(1) it is robust lang whose rich setup of built in functions and operator can be used
to write any complex prog.
(2)prog written in c are efficient due to several variety of data types and powerful
operators.
(3)the c complier combines the capabilities of an assembly lang with the feature of
hige level language. Therefore it is well suited for writing both system software
and business package.
(4)there r only 32 keywords, several standard functions r available which can be
used for developing prog.
(5)c is portable lang , this means that c programes written for one computer system
can be run on another system, with little or no modification.
(6)c lang is well suited for structured programming, this requires user to think of a
problems in terms of function or modules or block. A collection of these modules
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 1
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
Character set of C
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 2
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
ALPHABETS
Uppercase letters A-Z
Lowercase letters a-z
DIGITS 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
SPECIAL CHARACTERS
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 3
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
WHITESPACE CHARACTERS
Blank Space, Horizontal Tab, Vertical Tab, Carriage Return, New Line, Form
Feed(„ „, „\t‟,‟\v‟,‟\r‟, „\n‟, „\f‟
Certain ASCII characters are unprintable, which means they are not displayed on
the screen or printer. Those characters perform other functions aside from
displaying text. Examples are backspacing, moving to a newline, or ringing a bell.
They are used in output statements. Escape sequence usually consists of a
backslash and a letter or a combination of digits. An escape sequence is considered
as a single character but a valid character constant.
These are employed at the time of execution of the program. Execution characters
set are always represented by a backslash (\) followed by a character. Note that
each one of character constants represents one character, although they consist of
two characters. These characters combinations are called as escape sequence.
\\ - Back Slash
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 5
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
C tokens
the smallest individual unit in a c program is known as a token or a lexical unit. C
tokens can be classified as follows:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
C Keywords
C keywords are the words that convey a special meaning to the c compiler. The
keywords cannot be used as variable names because by doing so, we are trying to
assign a new meaning to the keyword which is not allowed.
C Identifiers
Identifiers are used as the general terminology for the names of variables, functions
and arrays. These are user defined names consisting of arbitrarily long sequence of
letters and digits with either a letter or the underscore(_) as a first character.
There are certain rules that should be followed while naming c identifiers:
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 6
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
Name Remark
_A9 Valid
Temp.var Invalid as it contains special character other than the underscore
void Invalid as it is a keyword
C Constants
C constants refers to the data items that do not change their value during the
program execution. Several types of C constants that are allowed in C are:
1. Integer Constants
Integer constants are whole numbers without any fractional part. It must have at
least one digit and may contain either + or – sign. A number with no sign is
assumed to be positive.
There are three types of integer constants:
1.1. Decimal Integer Constants
Integer constants consisting of a set of digits, 0 through 9, preceded by an optional
– or + sign.
Example of valid decimal integer constants
341, -341, 0, 8972
1.2. Octal Integer Constants
Integer constants consisting of sequence of digits from the set 0 through 7 starting
with 0 is said to be octal integer constants.
Example of valid octal integer constants
010, 0424, 0, 0540
1.3. Hexadecimal Integer Constants
Hexadecimal integer constants are integer constants having sequence of digits
preceded by 0x or 0X. They may also include alphabets from A to F representing
numbers 10 to 15.
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 7
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
b Backspace
f Form feed
n New line
r Carriage return
t Horizontal tab
v Vertical tab
\ Backslash
“ Double quotation mark
„ Single quotation mark
? Question mark
Null
String Constants
String constants are sequence of characters enclosed within double quotes. For
example,
“hello”
“abc”
“hello911”
Special Symbols
The following special symbols are used in C having some special meaning and
thus, cannot be used for some other purpose.
[] () {} , ; : * … = #
Braces{}: These opening and ending curly braces marks the start and end of a
block of code containing more than one executable statement.
Parentheses(): These special symbols are used to indicate function calls and
function parameters.
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 9
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
Brackets[]: Opening and closing brackets are used as array element reference.
These indicate single and multidimensional subscripts.
C Operators
C operators are symbols that triggers an action when applied to C variables and
other objects. The data items on which operators act upon are called operands.
Depending on the number of operands that an operator can act upon, operators can
be classified as follows:
1. Unary Operators: Those operators that require only single operand to act
upon are known as unary operators.
2. Binary Operators: Those operators that require two operands to act upon
are called binary operators.
3. Ternary Operators: These operators requires three operands to act upon.
C data types
C data types are defined as the data storage format that a variable can store
a data to perform a specific operation.
Data types are used to define a variable before to use in a program.
C – data types:
integer
Integer data type allows a variable to store numeric values.
“int” keyword is used to refer integer data type.
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 10
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
Floating Point
Variables of floating types can hold real values(numbers) such as: 2.34, -9.382 etc.
Keywords either float or double is used for declaring floating type variable.
“float” & “double” keyword is used to refer float & double data type.
Void Type
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 11
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
The void type has no value. This is usually used to specify the type of functions.
The type of a function is said to be void when it does not return any value to
calling function.
Modifiers in C:
In c language Data Type Modifiers are keywords used to change the properties of
current properties of data type. Data type modifiers are classified into following
types.
long
short
unsigned
signed
Modifiers are prefixed with basic data types to modify (either increase or
decrease) the amount of storage space allocated to a variable.
long:
This can be used to increased size of the current data type to 2 more bytes, which
can be applied on int or double data types. For example int occupy 2 byte of
memory if we use long with integer variable then it occupy 4 byte of memory.
short
In general int data type occupies different memory spaces for a different operating
system; to allocate fixed memory space short keyword can be used .
unsigned
This keyword can be used to make the accepting values of a data type is positive
data type.
signed
This keyword accepts both negative or positive value and this is default properties
or data type modifiers for every data type.
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 12
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 13
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
C OPERATORS
1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bit wise operators
6. Conditional operators (ternary operators)
7. Increment/decrement operators
8. Special operators
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 14
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
Arithmetic operators
C supports all the basic arithmetic operators. The following table shows all the
basic arithmetic operators.
Operator Description
+ adds two operands
- subtract second operands from first
* multiply two operand
/ divide numerator by denumerator
% remainder of division
Relation operators
Operator Description
== Check if two operand are equal
!= Check if two operand are not equal.
> Check if operand on the left is greater than operand on the right
< Check operand on the left is smaller than right operand
>= check left operand is greater than or equal to right operand
<= Check if operand on left is smaller than or equal to right operand
Logical operators
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 15
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
Assignment Operators
The above operator ( +=, -=, *=, /= , %= ) are shorthand assignment operators.
Operator Description
++ Increment operator increases integer value by one
-- Decrement operator decreases integer value by one
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 16
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
Bitwise operators
Bitwise operators perform manipulations of data at bit level. These operators also
perform shifting of bits from right to left. Bitwise operators are not applied to
float or double.
Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< left shift
>> right shift
Special operator
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 17
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
Typecasting
Typecasting concept in C language is used to modify a variable from one date type
to another data type. New data type should be mentioned before the variable
name or value in brackets which to be typecast.
Conversion between data types can be done in two ways by casting:
Implicit casting
Explicit casting
Implicit casting
Implicit casting doesn't require a casting operator. This casting is normally used
when converting data from smaller integral types to larger or derived types to the
base type.
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 18
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
he sequence of rules that are applied while evaluating expressions are given below:
All short and char are automatically converted to int, then,
1. If either of the operand is of type long double, then others will be converted to long
double and result will be long double.
2. Else, if either of the operand is double, then others are converted to double.
3. Else, if either of the operand is float, then others are converted to float.
4. Else, if either of the operand is unsigned long int, then others will be converted to
unsigned long int.
5. Else, if one of the operand is long int, and the other is unsigned int, then
1. if a long int can represent all values of an unsigned int, the unsigned int is
converted to long int.
2. otherwise, both operands are converted to unsigned long int.
6. Else, if either operand is long int then other will be converted to long int.
7. Else, if either operand is unsigned int then others will be converted to unsigned int.
It should be noted that the final result of expression is converted to type of variable
on left side of assignment operator before assigning value to it.
Also, conversion of float to int causes truncation of fractional part, conversion of
double to float causes rounding of digits and the conversion of long int to int
causes dropping of excess higher order bits.
Explicit casting
Explicit casting requires a casting operator. This casting is normally used when
converting a double to int or a base type to a derived type.
double y = 123;
int x = (int)y;
In the above statement, we have to specify the type operator (int) when
converting from double to int .
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 19
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
The following rules have to be followed while converting the expression from one
type to another to avoid the loss of information:
Decision making in C
Decision making is about deciding the order of execution of statements based on
certain conditions or repeat a group of statements until certain specified conditions
are met. C language handles decision-making by supporting the following
statements,
if statement
switch statement
conditional operator statement
goto statement
Simple if statement
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 20
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
if...else statement
The general form of a simple if...else statement is,
if( expression )
{
statement-block1;
}
else
{
statement-block2;
}
If the 'expression' is true, the 'statement-block1' is executed, else 'statement-block1'
is skipped and 'statement-block2' is executed.
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 21
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
if( expression )
{
if( expression1 )
{
statement-block1;
}
else
{
statement-block 2;
}
}
else
{
statement-block 3;
}
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 22
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
else-if ladder
The general form of else-if ladder is,
if(expression 1)
{
statement-block1;
}
else if(expression 2)
{
statement-block2;
}
else if(expression 3 )
{
statement-block3;
}
else
default-statement;
The expression is tested from the top(of the ladder) downwards. As soon as the
true condition is found, the statement associated with it is executed.
Switch statement
Switch statement is used to solve multiple option type problems for menu like
program, where one value is associated with each option. The expression in switch
case evaluates to return an integral value, which is then compared to the values in
different cases, where it matches that block of code is executed, if there is no
match, then default block is executed. The general form of switch statement is,
switch(expression)
{
case value-1:
block-1;
break;
case value-2:
block-2;
break;
case value-3:
block-3;
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 23
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
break;
case value-4:
block-4;
break;
default:
default-block;
break;
}
We don't use those expressions to evaluate switch case, which may return
floating point values or strings.
It isn't necessary to use break after each block, but if you do not use it, all the
consecutive block of codes will get executed after the matching block.
Goto statement
Flow Diagram
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 24
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
Looping
while(condition)
{
statement(s);
}
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 25
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
Flow Diagram
For loop
This is one of the most frequently used loop in C programming. It is also entry
controlled loop. The syntax of for loop is –
After the body of the 'for' loop executes, the flow of control jumps back up to the
increment statement. This statement allows you to update any loop control
variables. This statement can be left blank, as long as a semicolon appears after the
condition.
The condition is now evaluated again. If it is true, the loop executes and the
process repeats itself (body of loop, then increment step, and then again condition).
After the condition becomes false, the 'for' loop terminates.
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 27
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
Do while loop
Unlike for and while loops, which test the loop condition at the top of the loop, the
do...while loop in C programming checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except the fact that it is guaranteed to
execute at least one time. So it is known as exit controlled loop.
Syntax
The syntax of a do...while loop in C programming language is −
do
{
statement(s);
} while( condition );
The conditional expression appears at the end of the loop, so the statement(s) in the
loop executes once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the
statement(s) in the loop executes again. This process repeats until the given
condition becomes false.
Flow Diagram
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 28
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
A loop inside another loop is known as nested loop. We can write any loop inside
any loop in c i.e. we can write for loop inside the loop or while loop or do while
loop etc.
statement(s);
}
The syntax for a nested while loop statement in C programming language is as
follows −
while(condition) {
while(condition) {
statement(s);
}
statement(s);
}
The syntax for a nested do...while loop statement in C programming language is
as follows −
do {
statement(s);
do {
statement(s);
}while( condition );
}while( condition );
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 29
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
Arrays
Types of C arrays:
There are 2 types of C arrays. They are,
1. One dimensional array
2. Multi dimensional array
1. Two dimensional array
2. Three dimensional array, four dimensional array etc…
1. One dimensional array in C:
A list of item can be given one variable name using only on subscript is called one
dimensional array.
Like any other variable, arrays must be declared before they are used. General
form of array declaration is,
data-type variable-name[size];
for example :
int arr[10];
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 30
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
Here int is the data type, arr is the name of the array and 10 is the size of array. It
means array arr can only contain 10 elements of int type. Index of an array starts
from 0 to size-1 i.e first element of arr array will be stored at arr[0] address and
last element will occupy arr[9].
Initialization of an Array
After an array is declared it must be initialized. Otherwise, it will contain garbage
value(any random value). An array can be initialized at either compile time or at
runtime.
Multidimensional array
1. Array having more than one subscript variable is called multidimensional array.
2. Multidimensional array is also called as matrix.
Consider the Two dimensional array –
1. Two Dimensional Array requires Two Subscript Variables
2. Two Dimensional Array stores the values in the form of matrix.
3. One Subscript Variable denotes the “Row” of a matrix.
4. Another Subscript Variable denotes the “Column” of a matrix.
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 31
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
Example
int a[2][2]
Strings in C
char a[10]=”rajiv”;
r a j i v \0
0 1 2 3 4 5
char c[20];
scanf("%s",c);
String variable c can only take a word. It is because when white space is
encountered, the scanf() function terminates.
C String functions:
String.h header file supports all the string functions in C language. All the
string functions are given below.
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 32
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
strcat()
The strcat function joins two strings together. It takes the following form:
strcat(string1,string2);
string1 and string2 are character array. When function strcat is executed, string2 is
appended to string1. It does so by removing the null character at the of string1 and
placing string2 from there. The string2 remain unchanged.
strcpy()
The strcpy function work almost like a string assignment operator. It take the
form:
strcpy(string1,string2);
string1 and string2 are character array. When function strcpy is executed, the
content of string is copied to string1.
strcmp()
The strcmp function compares two strings identified by the arguments and has a
value 0 if they are equal. If they are not, it has the positive value if first string is
bigger & negative if first is smaller. It has the numeric difference between the first
non matching characters in the string.
strcmp(string1,string2)
strlen()
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 33
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
this function counts and returns the number of characters in a string. It takes
the form
n=strlen(string)
where n is a integer variable, which receives the value of length of string. The
argument may be string constant. The counting ends at the first null
character.
Functions
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 34
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
Library functions are those functions which are defined by C library, example
printf(), scanf(), strcat() etc. You just need to include appropriate header files to
use these functions. These are already declared and defined in C libraries.
User-defined functions are those functions which are defined by the user at the
time of writing program. Functions are made for code reusability and for saving
time and space.
Defining a Function
The general form of a function definition in C programming language is as follows
−
return_type function_name( parameter list )
{
body of the function
}
A function definition in C programming consists of a function header and a
function body. Here are all the parts of a function –
A. Return Type − A function may return a value. The return type is the data
type of the value the function returns. Some functions perform the desired
operations without returning a value. In this case, the return type is the
keyword void.
B. Function Name − This is the actual name of the function. The function
name and the parameter list together constitute the function signature.
C. Parameters − A parameter is like a placeholder. When a function is
invoked, you pass a value to the parameter. This value is referred to as actual
parameter or argument. The parameter list refers to the type, order, and
number of the parameters of a function. Parameters are optional; that is, a
function may contain no parameters.
D. Function Body − The function body contains a collection of statements that
define what the function does.
Function Declarations
A function declaration tells the compiler about a function name and how to call the
function. The actual body of the function can be defined separately.
A function declaration has the following parts −
return_type function_name( parameter list );
For the above defined function max(), the function declaration is as follows −
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 35
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
1 This method copies the actual value of an argument into the formal parameter of the
function. In this case, changes made to the parameter inside the function have no effect on
the argument.
Call by reference
2 This method copies the address of an argument into the formal parameter. Inside the
function, the address is used to access the actual argument used in the call. This means that
changes made to the parameter affect the argument.
By default, C uses call by value to pass arguments. In general, it means the code
within a function cannot alter the arguments used to call the function.
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 36
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
function-body
The function body contains the declarations and the statement(algorithm)
necessary for performing the required task. The body is enclosed within curly
braces { } and consists of three parts.
local variable declaration.
function statement that performs the tasks of the function.
a return statement that return the value evaluated by the function.
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 37
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
C - Storage Classes
A storage class defines the scope (visibility) and life-time of variables and/or
functions within a C Program. They precede the type that they modify. We have
four different storage classes in a C program −
auto
register
static
extern
Automatic variables
A variable declared inside a function without any storage class specification, is by
default an automatic variable. They are created when a function is called and are
destroyed automatically when the function exits. Automatic variables can also be
called local variables because they are local to a function. By default they are
assigned garbage value by the compiler.
Register variable
Register variables are similar to automatic variable and exists inside that particular
function only.
If the compiler encounters register variable, it tries to store variable in
microprocessor's register rather than memory. Value stored in register are much
faster than that of memory. Since, there are limited number of register in processor
and if it couldn't store the variable in register, it will automatically store it in
memory.
NOTE : We can never get the address of such variables.
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 38
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
Static variables
A static variable tells the compiler to persist the variable until the end of program.
Instead of creating and destroying a variable every time when it comes into and
goes out of scope, static is initialized only once and remains into existence till the
end of program. A static variable can either be internal or external depending upon
the place of declaration. Scope of internal static variable remains inside the
function in which it is defined. External static variables remain restricted to scope
of file in each they are declared.
They are assigned 0 (zero) as default value by the compiler.
Recursion
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 39
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
Structure
Defining a structure
struct keyword is used to define a structure. struct define a new data type which is
a collection of different type of data.
Syntax :
struct structure_name
{
Data type member 1;
Data type member 2;
};
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 40
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
Structure Initialization
Like any other data type, structure variable can also be initialized at compile time.
struct Patient
{
float height;
int weight;
int age;
};
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 41
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
Array of structure
union
A union is a special data type available in C that allows to store different data
types in the same memory location. You can define a union with many members,
but only one member can contain a value at any given time. Unions provide an
efficient way of using the same memory location for multiple-purpose.
Defining a Union
To define a union, you must use the union statement in the same way as you did
while defining a structure. The union statement defines a new data type with more
than one member for your program. The format of the union statement is as
follows −
union [union tag] {
member definition;
member definition;
...
member definition;
} [one or more union variables];
The union tag is optional and each member definition is a normal variable
definition, such as int i; or float f; or any other valid variable definition. At the end
of the union's definition, before the final semicolon, you can specify one or more
union variables but it is optional.
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 42
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
Unions in C Language
Unions are conceptually similar to structures. The syntax of union is also similar
to that of structure. The only differences is in terms of storage. In structure each
member has its own storage location, whereas all members of union uses a single
shared memory location which is equal to the size of its largest data member.
This implies that although a union may contain many members of different types,
it cannot handle all the members at same time. A union is declared using union
keyword.
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 43
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
Pointer
Normal variable stores the value whereas pointer variable stores the address of the
variable.
The content of the C pointer always be a whole number i.e. address.
Always C pointer is initialized to null, i.e. int *p = null.
The value of null pointer is 0.
& symbol is used to get the address of the variable.
* symbol is used to get the value of the variable that the pointer is pointing to.
If pointer is assigned to NULL, it means it is pointing to nothing.
Two pointers can be subtracted to know how many elements are available between
these two pointers.
But, Pointer addition, multiplication, division are not allowed.
The size of any pointer is 2 byte (for 16 bit compiler).
Concept of Pointer
int a = 10 ;
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 44
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
We can access the value 10 by either using the variable name a or the address 80F.
Since the memory addresses are simply numbers they can be assigned to some
other variable. The variable that holds memory address are called pointer
variables. A pointer variable is therefore nothing but a variable that contains an
address, which is a location of another variable. Value of pointer variable will be
stored in another memory location.
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 45
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
In arrays of C programming, name of the array always points to the first element of
an array. Here, address of first element of an array is &arr[0]. Also, arr represents
the address of the pointer where it is pointing. Hence, &arr[0] is equivalent to arr.
Also, value inside the address &arr[0] and address arr are equal. Value in address
&arr[0] is arr[0] and value in address arr is *arr. Hence, arr[0] is equivalent to
*arr.
Similarly,
&a[1] is equivalent to (a+1) AND, a[1] is equivalent to *(a+1).
&a[2] is equivalent to (a+2) AND, a[2] is equivalent to *(a+2).
&a[3] is equivalent to (a+1) AND, a[3] is equivalent to *(a+3).
.
.
&a[i] is equivalent to (a+i) AND, a[i] is equivalent to *(a+i).
In C, you can declare an array and can use pointer to alter the data of an array.
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 46
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
Pointer to Structure
Like we have array of integers, array of pointer etc, we can also have array of
structure variables. And to make the use of array of structure variables efficient, we
use pointers of structure type. We can also have pointer to a single structure
variable, but it is mostly used with array of structure variables.
Accessing Structure Members with Pointer
To access members of structure with structure variable, we used the dot . operator.
But when we have a pointer of structure type, we use arrow -> to access structure
members. The symbol -> is known as arrow operator(member selection operator)
Although, C language inherently does not has any technique to allocated memory
dynamically, there are 4 library functions under "stdlib.h" for dynamic memory
allocation.
malloc()
The name malloc stands for "memory allocation". The function malloc() reserves a
block of memory of specified size and return a pointer of type void which can be
casted into pointer of any form.
Syntax of malloc()
ptr=(cast-type*)malloc(byte-size)
Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area
of memory with size of byte size. If the space is insufficient, allocation fails and
returns NULL pointer.
ptr=(int*)malloc(100*sizeof(int));
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 47
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes
respectively and the pointer points to the address of first byte of memory.
calloc()
The name calloc stands for "contiguous allocation". The only difference between
malloc() and calloc() is that, malloc() allocates single block of memory whereas
calloc() allocates multiple blocks of memory each of same size and sets all bytes to
zero.
Syntax of calloc()
ptr=(cast-type*)calloc(n,element-size);
free()
Dynamically allocated memory with either calloc() or malloc() does not get return
on its own. The programmer must use free() explicitly to release space.
syntax of free()
free(ptr);
This statement cause the space in memory pointer by ptr to be deallocated
realloc()
If the previously allocated memory is insufficient or more than sufficient. Then,
you can change memory size previously allocated using realloc().
Syntax of realloc()
ptr=realloc(ptr,newsize);
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 48
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
FILE HANDLING IN C
A file represents a sequence of bytes on the disk where a group of related data is
stored. File is created for permanent storage of data. It is a ready made structure.
In C language, we use a structure pointer of file type to declare a file.
FILE *fp;
C provides a number of functions that helps to perform basic file operations.
Following are the functions,
Function description
fopen() create a new file or open a existing file
fclose() closes a file
getc() reads a character from a file
putc() writes a character to a file
fscanf() reads a set of data from a file
fprintf() writes a set of data to a file
getw() reads a integer from a file
putw() writes a integer to a file
fseek() set the position to desire point
ftell() gives current position in the file
rewind() set the position to the begining point
The fopen() function is used to create a new file or to open an existing file.
General Syntax :
*fp = FILE *fopen(const char *filename, const char *mode);
Here filename is the name of the file to be opened and mode specifies the purpose
of opening the file. Mode can be of following types,
*fp is the FILE pointer (FILE *fp), which will hold the reference to the opened(or
created) file.
mode description
r opens a text file in reading mode
w opens or create a text file in writing mode.
a opens a text file in append mode
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 49
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
Closing a File
General Syntax :
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 50
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
Preprocessor
C Preprocessor directives:
Before a C program is compiled in a compiler, source code is processed by a
program called preprocessor. This process is called preprocessing.
Commands used in preprocessor are called preprocessor directives and they begin
with “#” symbol.
Below is the list of preprocessor directives that C language offers.
S.no Preprocessor Syntax Description
This macro defines constant value and
1 Macro #define
can be any of the basic data types.
The source code of the file “file_name”
Header file #include
2 is included in the main program at the
inclusion <file_name>
specified place
Set of commands are included or
Conditional #ifdef, #endif, #if, excluded in source program before
3
compilation #else, #ifndef compilation with respect to the
condition
#undef is used to undefine a defined
macro variable. #Pragma is used to call
4 Other directives #undef, #pragma
a function before and after main
function in a C program
Macro Substitution
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 51
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
We have written all macro identifier in capital. It is a convention to write all macro
in capital to identify them as symbolic constants.
A macro definition can include more than a simple constant value, it can include
expressions also.
#define AREA 5*12.45
The preprocessor permits us to define more complex and more useful form of
replacement. It takes the form:
#define identifier(f1,f2,....fn) string
Notice that there is no space between the macro identifier and left parenthesis. The
identifier f1,f2,...,fn are the formal macro arguments that are analogous to formal
arguments in a function definition.
There is basic difference between the simple replacement & replacement of macros
with arguments. Subsequent occurrence of macro with arguments is known as
macro call. When a macro is called, the preprocessor substitutes the string,
replacing the formal parameters with actual parameter. Hence, the string behaves
like a template.
#define CUBE( x) (x*x*x)
Nesting of macro
We can also use one macro in definition of another macro. That is, macro
definition may be nested.
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 52
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
#define M 5
#define N M+1
The preprocessor expands each #define macro, until no more macro appear in the
text.
FILE INCLUSION
An external file containing functions or macro definition can be included as a part
of program so that we need not rewrite those functions or macro definitions. This is
achieved by preprocessor directive
#include “filename”
Where filename is the name of the file containing required definitions or functions.
At this point, the preprocessor insert the entire content of filename into the source
code of the program. When filename is included with the double quotation marks,
the search for file is made first in the current directory and then in standard
directories.
Alternatively this directive can taken form
#include <filename>
Without double quotation marks. In this case, the file is searched only in the
standard directories.
or
#if constant_expression
#elif constant_expression
#endif
The compiler only compiles the code after the #if expression if the
constant_expression evaluates to a non-zero value (true). If the value is 0 (false),
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 53
C LANGUAGE
SITI COMPUTERS (H.NO 5 NEW COLONY PALWAL)
then the compiler skips the lines until the next #else, #elif, or #endif. If there is a
matching #else, and the constant_expression evaluated to 0 (false), then the lines
between the #else and the #endif are compiled. If there is a matching #elif, and the
preceding #if evaluated to false, then the constant_expression after that is
evaluated and the code between the #elif and the #endif is compiled only if this
expression evaluates to a non-zero value (true).
Examples:
int main(void)
{
#if 1
printf("Yabba Dabba Do!\n");
#else
printf("Zip-Bang!\n");
#endif
return 0;
}
#undef identifier
#ifdef identifier
#else or #elif
#endif
#ifndef identifier
#else or #elif
#endif
M: +91+9315385361, +91-9802336315
siticomputerspwl@gmail.com Page 54