C Module 1 Notes
C Module 1 Notes
Module 1
Overview of C
A Brief History of C.
➢ C was invented and first implemented by Dennis Ritchie on a DEC PDP-11 that used the Unix
operating system.
➢ C is the result of a development process that started with an older language called BCPL.
➢ Martin Richards developed BCPL(“Basic Combined Programming Language”), which
influenced a language called B, invented by Ken Thompson.
➢ B led to the development of C in the 1970s.
➢ For many years, the de facto standard for C was the version supplied with the Unix operating
system.
➢ It was first described in The C Programming Language by Brian Kernighan and Dennis Ritchie
➢ In 1983, a committee was established to create an ANSI (American National Standards Institute)
standard that would define the C language.
➢ The standardisation process took six years (much longer than expected).
➢ The ANSI C standard was finally adopted in December 1989, with the first copies becoming
available in early 1990.
➢ The standard was also adopted by ISO (International Standards Organisation), and the resulting
standard was typically referred to as ANSI/ISO Standard C.
➢ In 1995, Amendment 1 to the C standard was adopted, which added several new library functions.
➢ The 1989 standard for C, along with Amendment 1, became a base document for Standard C++,
defining the C subset of C++.
➢ The version of C defined by the 1989 standard is commonly referred to as C89.
➢ work on C continued quietly, leading to a new standard — the 1999 standard for C, usually
referred to as C99. C99 retained nearly all of the features of C89.
BIT, Bengaluru-04 1
1BEIT105
C Is a Middle-Level Language
➢ C as a middle-level language, allows the programmers to work directly with bits, bytes, and
memory addresses.
➢ C code is also very portable. Portability means that it is easy to adapt software written for
one type of computer or operating system to another type.
➢ All high-level programming languages support the concept of data types. A data type
defines a set of values that a variable can store along with a set of operations that can be
performed on that variable.
➢ Common data types: int (integer), char (character), and float (decimal numbers). C also
allows automatic type conversions.
➢ Although C has several built in data types, it is not a strongly typed language, as are
Pascal and Ada.
➢ C is special in that it allows the direct manipulation of bits, bytes, words, and pointers. This
makes it well suited for system-level programming.
BIT, Bengaluru-04 2
1BEIT105
➢ C has only a small number of keywords (reserved words used by the language). C89 has 32
keywords, and C99 adds 5 more (total 37). In comparison, BASIC has over 100 keywords!
fewer keywords make C simpler and more flexible.
C Is a Structured Language
➢ Structured Language: A structured language helps you organize a program into smaller, clear
parts.C is called a structured language, even though it’s not fully block-structured. It is similar
to other structured languages like Pascal, ALGOL, and Modula-2.
➢ C is Not Fully Block-Structured: In block-structured languages, one function can be declared
inside another function. But in C, we cannot create a function inside another function because
of this C is called as structured, but not fully block-structured.
➢ Compartmentalization: C programming language supports compartmentalization means
dividing a program into small sections (modules). Each section performs one specific task.
This makes programs easy to understand, test, and debug. One way to achieve
compartmentalization is by using subroutines that employ local (temporary) variables.
➢ Functions and Local Variables: The main structural unit in C is the function. A function
performs one specific task. Each function can work independently without affecting others.
This makes C programs modular and reusable. We can use functions to divide the program
into smaller parts. Local variables (declared inside a function) are used only in that function.
This prevents side effects (changes that affect other parts of the program). Using too many
global variables (variables known throughout the entire program) can cause errors or confusion
in large programs.
➢ Features of Structured Languages: Structured languages provide different loops: while, do-
while, for. The use of goto is discouraged (it makes code confusing). Structured languages are
modern and easier to maintain. Old languages are usually non-structured and harder to use.
➢ Code Blocks in C: Another way to structure code is by using blocks — a group of
statements inside curly braces { }.
BIT, Bengaluru-04 3
1BEIT105
C is a Programmer's Language
BIT, Bengaluru-04 4
1BEIT105
➢ C vs Assembly Language
➢ Early Use of C
o Initially used for systems programming, such as:
▪ Operating systems
▪ Compilers
▪ Editors
▪ Utilities
o As C became popular, it was used for all types of programming due to:
▪ Efficiency
▪ Portability
▪ Programmer preference
➢ Significance of C
o C remains one of the most influential and foundational programming languages.
o It laid the groundwork for many modern languages like C++, Java, and Python.
o It will always be remembered as:
▪ The foundation of C++, and
▪ A powerful, efficient, and universal language for programmers.
BIT, Bengaluru-04 5
1BEIT105
BIT, Bengaluru-04 6
1BEIT105
➢
➢ They define the syntax and structure of the C programming language.
➢ Keywords cannot be used as variable names, function names, or identifiers.
➢ C89 (ANSI C) Standard
o Defined 32 keywords that form the core of the C language.
o These are also part of the C subset of C++.
➢ C99 Standard
o Added 5 new keywords to enhance functionality.
o
_Bool _Complex _Imaginary inline restrict o
➢ Total C keywords after C99 = 37
➢ Case Sensitivity
o C treats uppercase and lowercase letters as different.
▪ else → valid keyword
▪ ELSE → invalid
o Therefore, be careful while writing C code — keywords must be in lowercase.
➢ Structure of a C Program
o Every C program consists of one or more functions.
o The main( ) function is essential — it is the starting point of execution.
o Execution begins with:
int main()
{
// statements
return 0;
}
BIT, Bengaluru-04 7
1BEIT105
Concept Details
Total Keywords (C89) 32
Keywords Added in C99 5
Total Keywords (C99) 37
Case Sensitivity Yes (else ≠ ELSE)
Nonstandard Keywords Compiler-specific (e.g., asm, far, pascal)
Essential Function main() — entry point of program
Program Structure Header → main() → function calls
BIT, Bengaluru-04 8
1BEIT105
o Some compilers include a built-in linker, while others rely on the linker from the
operating system.
o During linking, the linker assigns actual memory addresses based on where the
program will run.
o This process ensures that the same library code can be used by many programs
without rewriting it.
o We can also create your own library by collecting functions that you use frequently.
Example:
If we write several programs that all use a factorial() function,
we can store it in a library and reuse it in multiple programs.
#include <stdio.h>
#include <math.h>
int main()
{
double num = 16.0;
double result = sqrt(num); // sqrt() is a standard library function
printf("Square root of %f = %f", num, result);
return 0;
}
C program is composed of processor command, global declarative section and one or more function
blocks. The preprocessor directives are instructions that indicate how the program has to be compiled.
include is one the preprocessor command through which the compiler include the needed information from
the specified header file to the particular code.
In Global variables or constants can be declared in the global declaration part.
C program contains one or more functions. Functions are defined as a group of statements that are executed
together. Function can be either system defined or user defined functions. All functions are divided into
two parts:
Local declaration section: Data will be visible only within that function. Stated in other terms, the life-
time of the data will be only till the function ends.
Statement section: Contains the code that manipulates the data to perform a specified task.
main() function is a system defined function from which the C program execution begins.
BIT, Bengaluru-04 9
1BEIT105
Every C program must include one main function, where as user defined functions can be of any number
which can be included based on the tasks to be performed.
Separate Compilation
➢ In small programs, all code is usually written in one source file (e.g., program.c).
➢ As programs grow larger, compiling the entire program every time becomes slow and
inefficient.
➢ To solve this, C allows separate compilation — meaning the program can be split across
multiple source files, and each file can be compiled separately.
➢ Each source file (e.g., main.c, file1.c, file2.c) is compiled individually into an object file (.obj
OR .o).
➢ After all files are compiled, the linker combines:
▪ All object files
▪ Any required library routines to form one final executable file.
➢ Advantages of Separate Compilation
Advantage Explanation
Faster recompilation Only changed files need recompilation. Saves time on large projects.
Team collaboration Multiple programmers can work on different files simultaneously.
Better organization Code can be divided into logical modules, making maintenance easier.
BIT, Bengaluru-04 10
1BEIT105
Advantage Explanation
Efficient debugging Errors can be traced in smaller, individual files.
Compiling a C Program
BIT, Bengaluru-04 11
1BEIT105
When a C program is compiled and executed, it uses four logically distinct regions of memory.
Each region serves a specific purpose during program execution.
BIT, Bengaluru-04 12
1BEIT105
➢ Floating-Point Representation
o The exact format of float and double depends on how the compiler implements them.
o Minimum range for floating-point numbers: 1E–37 to 1E+37.
o float and double differ in precision (number of digits they can represent accurately).
➢ Character Data
o char usually represents ASCII characters.
o Values outside the ASCII range may behave differently depending on the compiler.
➢ Void Type
o void is used for:
BIT, Bengaluru-04 13
1BEIT105
➢ Except for the type void, all basic data types in C can have modifiers.
A type modifier changes the meaning of a base type to better fit a specific need.
➢ The available modifiers are:
o signed
o unsigned
o long
o short
➢ The base type int can be modified by:
→ signed, unsigned, short, long
➢ The base type char can be modified by:
→ signed, unsigned
➢ The base type double can be modified by:
→ long
➢ In C99, long long is also allowed for larger integer values.
BIT, Bengaluru-04 14
1BEIT105
➢ Using signed with integers is allowed but redundant, since integers are signed by default.
➢ The keyword signed is mainly used with char when the compiler defaults to unsigned char.
➢ Difference Between Signed and Unsigned
➢ Signed integers use the high-order bit (leftmost bit) as a sign flag:
o 0 → positive number
o 1 → negative number
➢ Most systems represent negative numbers using two’s complement:
o In two’s complement, all bits are reversed (except the sign bit), then 1 is added.
➢ Example:
o +32,767 in binary:
0 11111111 11111111
o If the high-order bit becomes 1, it represents –1 in signed form.
o But if declared as unsigned, the same bit pattern equals 65,535.
➢ If a modifier is written without a base type, int is assumed.
Specifier Same As
signed signed int
unsigned unsigned int
long long int
short short int
Identifier Names
➢ In C, the names of variables, functions, labels, and various other user-defined items are called
identifiers.
➢ The length of these identifiers can vary from one to several characters.
➢ The first character must be a letter or an underscore, and subsequent characters must be
either letters, digits, or underscores.
➢ Here are some correct and incorrect identifier names
BIT, Bengaluru-04 15
1BEIT105
➢ Types of Identifiers
o C defines two kinds of identifiers:
BIT, Bengaluru-04 16
1BEIT105
Local Variable
BIT, Bengaluru-04 17
1BEIT105
➢ The local variable is only accessible inside the function or block of code in which it is
declared. A variable's scope specifies where it can be used and accessible within a program .
In the above code, When the function is called from the main function, it prints the value of localVar as 10. If
you try to access it outside of its scope( in this example main function )will result in a compilation “error:
'localVar' undeclared”. This is referred to as being out of scope.
➢ Variables have a specified region or context in which they are valid and can be
manipulated. After a variable goes beyond its scope, it can no longer be accessed or
modified.
BIT, Bengaluru-04 18
1BEIT105
• Local variables are only usable within the scope in which they are declared, It avoids naming
conflicts and maintains code organization.
• Local variables are useful for storing temporary data that is only required within a particular
function or block of code.
• Local variables provide more security we can wrap the variables in a code block or function to
limit access of those variables to that scope only.
• Local variables can make the code easy to read.
BIT, Bengaluru-04 19
1BEIT105
Global Variables in C
• The Declaration of a global variable is very similar to that of a local variable. The only difference
is that the global variable is declared outside any function.
• The initialization of these variables occurs automatically to 0 during the time of declaration. Also,
we generally write the global variables before the main() function.
Outut : 25
BIT, Bengaluru-04 20
1BEIT105
return 0;
} //main function block ends
O/P:
The value of a in main function block: 10
The value of a in inner block: 20
The value of a in main function block: 10
Function • Identifiers declared in a function prototype; visible within the
prototype scope prototype
Example:
#include<stdio.h>
int add(int a, int b); // 'a' and 'b' have prototype scope
BIT, Bengaluru-04 21
1BEIT105
BIT, Bengaluru-04 22
1BEIT105
BIT, Bengaluru-04 23
1BEIT105
BIT, Bengaluru-04 24
1BEIT105
• In File 2, the global variables from File 1 are declared with extern, telling the compiler
they’re defined elsewhere. This prevents creating new storage, and the linker later
connects all references to these external variables.
2. static variables:
• Variables declared as static are permanent variables within their own function or file.
• Static variables keep their values between function calls but are only accessible within
their own function or file.
• They’re useful for creating reusable functions and libraries, and their effect differs for
local and global variables.
➢ static local variables
• A static local variable is stored permanently like a global variable but it will be visible
only within the block it declared, whereas global variable is visible throughout the
program.
• static local variable helps create stand-alone functions that retains its value between
function calls without using global variables.
• Using static variables prevents unwanted side effects from global variables.
• Commonly used in routines like number generators or counters that need to remember
past values.
Example:
Ex1: Ex2:
#include <stdio.h> #include <stdio.h>
void numberSeries() { int num = 0; //global varaiable
static int num = 0;//static local variable void numberSeries() {
num++; num++;
printf("Next number: %d\n", num); printf("Next number: %d\n", num);
} }
BIT, Bengaluru-04 25
1BEIT105
Output: Output:
Next number: 1 Next number: 1
Next number: 2 Next number: 2
Next number: 3 Next number: 4
BIT, Bengaluru-04 26
1BEIT105
Note: The names of local static variables are known only to the block of code in which
they are declared; the names of global static variables are known only to the file in
which they reside.
3. register Variables
• The register specifier tells the compiler to store a variable in the CPU register instead
of normal memory (RAM). This makes access to the variable faster, especially in loops
or frequently used operations.
• In Standard C register specifier can be used with any data type.
• Since register variables are stored in the CPU, reading and updating them takes less
time compared to normal variables in memory.
• You cannot use the address-of operator (&) with register variables because CPU
registers are not usually addressable.
• register specifier can be applied only to local variables and to the formal parameters in
a function. Global register variables are not allowed.
Example:
#include <stdio.h>
void main() {
register int i; // register variable (local)
int sum = 0;
int main() {
show();
return 0;
}
Output:
Value of num = 10
In this program num is an auto variable, local to show(). It exists only while show()
executes and is destroyed when the function ends.
❖ Variable Initialization:
• Assigning a value to a variable as you declare them by placing an equal sign and a
constant after the variable name is called variable initialization.
• The general form of initialization is
datatype variable_name = constant;
Example:
char ch = 'a'; //initialize ch variable with ‘a’ value
int first = 0; //initialize first variable with 0 value
double balance = 123.23; //initialize balance variable with 123.23 value
❖ Constants:
• Constants are identifiers whose values do not change. A constant is an explicit data value
specified by the programmer. Compiler knows the value of constant at compile time.
• Constants are used to define the values that shouldn’t be changed throughout the program
even by mistake.
• Types of Constants:
a) Integer Constant: A constant of integer type consists of a sequence of digits.
For example: 1, 34, 567, 8907 are valid integer constants.
• A literal integer like 1234 is of type int by default.
• For a Long integer constant the literal is succeeded with either ‘L’ or ‘l’ (like
1234567L).
• Similarly, an unsigned int literal is written with a ‘U’ or ‘u’ suffix (e.g. 12U).
1234L, 12341, 1234U, 1234u, 1234LU, 1234u) are all valid integer constants.
• By default an integer is expressed in decimal notation, Decimal integers consist
of a set of digits, 0 through 9, preceded by an optional - or + sign.
Examples of decimal integer constants include: 123, -123, +123, and 0.
BIT, Bengaluru-04 28
1BEIT105
BIT, Bengaluru-04 29
1BEIT105
The above table shows the decimal and hexadecimal ASCII value of each character.
e) String Constants: A string constant is a sequence of characters enclosed in double
quotes.
• When a string constant is encountered in a C program, the compiler records the
address of the first character and appends a null character (“\0”) to the string to
mark the end of the string.
• Thus, length of a string constant is equal to number of characters in the string plus
+ (for the null character), Therefore, the length of string literal "hello" is 6.
Example: “HELLO”
H E L L O \0
0 1 2 3 4 5
BIT, Bengaluru-04 30
1BEIT105
Example:
#include <stdio.h>
int main(void)
{
printf("\n\tThis is a test."); //prints newline, tab space and “This is a test.” characters.
return 0;
}
Output:
This is a test.
❖ Declaring Constants:
• To declare a constant, precede the normal variable declaration with const keyword
and assign it a value.
For example, “const float pi = 3.14;”
Note: The const keyword specifies that the value of pi cannot change.
• Another way to define constant is to use the pre-processor command define using ‘#’.
Example: “#define pi 3.14159”
• Rules that need to be applied to a #define statement which defines a constant:
Rule 1: No blank spaces are permitted between the # symbol and define keyword.
Rule 2: Blank space must be used between define and constant name and between
constant name and constant value.
Rule 3: #define is a pre-processor compiler directive and not a statement. Therefore, it
does not end with a semi-colon.
BIT, Bengaluru-04 31
1BEIT105
❖ Operators in C
An operator is a symbol that tells the compiler to perform specific mathematical, logical
or relational operations to be performed. The different operators supported in ‘C’ are:
1. Assignment Operator
2. Arithmetic Operator
3. Relational Operators
4. Logical Operators
5. Bitwise Operators
6. Ternary (?, :) Operator
7. Comma Operator
8. Compile-Time Operator sizeof
9. & and * Pointer Operators
10. Dot (.) and Arrow (–>) Operators
11. [ ] and ( ) Operators
a) Assignment Operator:
• Assignment operator ‘=’ can be used within any valid expression.
The general form of the assignment operator is
variable_name = expression;
lvalue rvalue
• lvalue is an object. If that object can occur on the left side of an assignment
statement, it is called a modifiable lvalue (means ''variable.").
• The term rvalue refers to expressions on the right side of an assignment and
simply means the value of an expression
➢ Type Conversion in Assignments:
• When variables of one type are mixed with variables of another type, a type
conversion will occur.
• In an assignment statement, the type conversion rule is easy: The value of the
right side (expression side) of the assignment is converted to the type of the left
side (target variable), as illustrated here:
#include<stdio.h>
void main()
{
int x;
char ch;
float f;
ch = x; //integer value is converted to character
x = f; //float value is converted to integer
f = ch; //character value is converted to float
f = x; //integer value is converted to float
}
▪ In ch=x, the left high-order bits of the integer variable x are lopped off,
leaving ch with the lower 8 bits.
▪ In x=f, x will receive the nonfractional part of f.
▪ In f = ch, f will convert the 8-bit integer value(of character) stored in ch to the
same value in the floating-point format.
▪ In f=x, convert an integer value into floating-point format.
BIT, Bengaluru-04 32
1BEIT105
➢ Multiple Assignments
We can assign many variables the same value by using multiple assignments in a
single statement.
For example, below program fragment assigns x, y, and z the value 0
x = y = z = 0;
➢ Compound Assignments
Compound assignment operators exist for all the binary operators (those that require
two operands). Compound assignment is also sometimes referred to as shorthand
assignment.
In general, statements like
variable1 = variable1 operator expression
can be rewritten as
variable1 operator = expression
Example 1:
x = x+10; ➔ can be rewritten as x+=10;
Example 2:
x = x-100; ➔ can be rewritten as x-=100;
b) Arithmetic Operator
• The operators that are used to perform arithmetic operations such as
addition, subtraction, multiplication, division, modulus, increment and
decrement operations are called Arithmetic operators.
• These operators perform operations on two operands and hence they are binary
operators.
The different arithmetic operators are:
Operator Name Result Syntax Example (b=5, c=2)
+ Addition Sum a=b+c a=7
- Subtraction / Difference a=b-c a=3
unary minus
* Multiplication Product a=b*c a = 10
/ Division Quotient a=b/c a=2
% Modulus Remainder a=b%c a=1
++ Increment Value a++ a=2
incremented by 1
-- Decrement Value a-- a=1
decremented by 1
• The modulus operator(%) finds the remainder of an integer division. This
operator can be applied only to the integer operands and cannot be used for
float or double operands.
• While performing modulo division, the sign of the result is always the sign
of first operand(the dividend).
16%3=1 16%-3=1 -16%3=-1 -16%-3=-1
• All the arithmetic operators bind from left to right. The multiplication,
division and modulus operators have higher precedence over addition and
subtraction.
BIT, Bengaluru-04 33
1BEIT105
BIT, Bengaluru-04 34
1BEIT105
• Operators on the same level of precedence are evaluated by the compiler from
left to right.
• parentheses to alter the order of evaluation. Parentheses force an operation,
or set of operations, to have a higher level of precedence.
c) Relational Operators
• We often compare two quantities and depending on their relation take
certain decisions. For example, we might compare the age of two persons,
or the price of two items, and so on. These comparisons can be done with
the help of relational operators.
• These operators are also known as comparison operator.
• The output will be either 0 (False) or 1 (True).
For example
a>b //If a is greater than b, then a>b returns 1 else a>b returns 0.
• The expression containing a relational operator is returned as a relational
expression.
• The 2 operands may be constants, variables or expressions.
• C supports two kinds of equality operators to compare their operands for strict
equality or inequality. They are equal to(= =) and not equal to(!=) operators.
• The equal to (= =) operator returns True if both the operands have same
value, else it returns False.
• The not equal to (!=) operator returns True if both the operands have
different value else it returns False.
• Relational operators are as listed below
Operator Name Syntax Example (b=5, c=2)
< Lesser than a=b<c a = 0 (False)
> Greater than a=b>c a = 1 (True)
<= Lesser than or Equal to a = b <= c a = 0 (False)
>= Greater than or Equal to a = b >= c a = 1 (True)
== Equal to a=b==c a = 0 (False)
!= Not equal to a = b != c a = 1 (True)
BIT, Bengaluru-04 35
1BEIT105
BIT, Bengaluru-04 36
1BEIT105
Input Output
X Y X (xor) Y
0 0 0
0 1 1
1 0 1
1 1 0
Program
#include<stdio.h>
void main()
{
int a, b, xor;
a=0, b=1;
xor = (a || b)&& !(a && b);
printf("%d xor %d = %d\n",a,b,xor);
a=1, b=1;
xor = (a || b)&& !(a && b);
printf("%d xor %d = %d\n",a,b,xor);
}
Output:
0 xor 1 = 1
0 xor 0 = 0
• Both the relational and logical operators are lower in precedence than the
arithmetic operators
• Precedence of the relational and logical operators:
Example:
1. 10 > 1+12 → Result is False(0) because ‘+’ operator have higher precedence
than ‘>’ operator.
2. !0 && 0 | | 0 → Evaluated to False(0)
3. !(0 && 0) | | 0 → Evaluated to True(1), because parentheses have higher
precedence level.
e) Bitwise Operators
• These works on bits and performs bit by bit operations.
• The different types of bitwise operators are:
i. Bitwise NOT (~) → One's complement
ii. Bitwise AND (&)
BIT, Bengaluru-04 37
1BEIT105
i. Bitwise AND (&) : The truth table is same as shown in logical AND operation. The
bitwise AND operator compares each bit of its first operand with the corresponding bit
of its second operand. If both bits are 1,the corresponding bit in result is 1 otherwise 0.
Example:
Binary value of 10 → 1010 (8 bit representation is ‘00001010’)
Binary value of 20 → 10100 (8 bit representation is ‘00010100’)
int a=10, b=20,c; a&b→ 00001010
c = a & b; → c = 0 00010100
___________________
00000000
ii. Bitwise OR ( | ): The bitwise OR operator compares each bit of its first operand with
the corresponding bit of its second operand. If both bits are 0, the corresponding bit in
result is 0 otherwise 1.
Example:
Binary value of 10 → 1010 (8 bit representation is ‘00001010’)
Binary value of 20 → 10100 (8 bit representation is ‘00010100’)
int a=10, b=20, c; a | b→ 00001010
c = a | b; → c = 30 00010100
___________________
00011110
iii. Bitwise XOR (^): The bitwise XOR operator compares each bit of its first operand
with the corresponding bit of its second operand. If one of the bit is 1, the corresponding
result bit is 1 otherwise 0.
Example:
Binary value of 10 → 1010 (8 bit representation is ‘00001010’)
Binary value of 20 → 10100 (8 bit representation is ‘00010100’)
int a=10, b=20, c; a ^ b→ 00001010
c = a ^ b; → c = 30 00010100
___________________
00011110
iv. Bitwise NOT (~): It is a unary operator, performs logical negation on each bit of
the operand i.e., one’s complement of each bit.
Example:
Binary value of 10 → 1010 (8 bit representation is ‘00001010’)
int a=10, c; ~a → 00001010
c = ~a; → c = -11 ___________________
11110101
BIT, Bengaluru-04 38
1BEIT105
v. Bitwise Left Shift (<<) : Shift specified number of bits to left side.
General form: variable << number of bit positions
Note: one left shift multiplies the number by 2.
Example:
X= 10 0 0 0 0 1 0 1 0
X<<2 → X=40 0 0 1 0 1 0 0 0
vi. Bitwise Right Shift (>>) : Shift specified number of bits to right side.
General form: variable >> number of bit positions
Note: one right shift divides the number by 2.
Example:
X= 10 0 0 0 0 1 0 1 0
X>>2 → X=2 0 0 0 0 0 0 1 0
Note: As bits are shifted off from one end, zeroes are brought in the other end. The bits
shifted off are lost.
BIT, Bengaluru-04 39
1BEIT105
BIT, Bengaluru-04 40
1BEIT105
Example:
Assume that the variable count is at memory location 2000. And count has a
value of 100.
int count=100, *m; // m is an integer pointer
m = &count; // m receives the address of variable count.
Result → m = 2000.
• The second pointer operator is *, a unary operator that returns the value of the
object located at the address that follows it (i.e., * as meaning "at address").
Example:
int count=100, *m, q; // m is an integer pointer
m = &count; // m receives the address of variable count.
q = *m // q has the value stored at location 2000
Result → q = 100
Example program:
#include <stdio.h>
int main(void)
{
int target, source;
int *m;
source = 10;
m = &source;
target = *m;
printf("%d", target);
return 0;
}
Output:
10
j) Dot (.) and Arrow (–>) Operators
• The . (dot) and the –> (arrow) operators access individual elements of structures
and unions.
• Structures and unions are compound data types that may be referenced under a
single name.
• The dot operator is used when working with a structure or union directly.
• The arrow operator is used with a pointer to a structure or union.
Example:
struct employee {
char name[80];
int age;
float wage;
} emp;
struct employee *p = &emp; // address of emp into p
o Dot (.) is used to assign the value 123.23 to the wage member of structure
variable emp:
emp.wage = 123.23;
o Arrow (->) is used to assign the value 123.23 to the wage member of
structure variable emp using pointer to emp (i.e., p):
p->wage = 123.23;
BIT, Bengaluru-04 41
1BEIT105
k) [ ] and ( ) Operators
• Parentheses are operators that increase the precedence of the operations inside
them.
Example:
int result = 5 + 3 * 2; // Evaluates to 11
int result = (5 + 3) * 2; // Evaluates to 16 since () increases the precedence
• Square brackets perform array indexing. Given an array, the expression within
square brackets provides an index into that array.
Example:
#include<stdio.h>
char s[80];
void main( ) {
s[3] = 'X'; // stores value 'X' to the fourth element of array s.
printf(''%c", s[3]); //prints the value stored in fourth element of array s
}
Output:
X
❖ Expressions
• Operators, constants, functions, and variables are the constituents of expressions.
An expression in C is any valid combination of these elements
• Precedence: The order in which operators are evaluated is based on the priority
value.
• Associativity: It is the parsing direction used to evaluate an expression. It can be
left to right orright to left.
• Evaluation of expressions: Expressions are evaluated using an assignment
statement.
Example: variable = expression
sum = a + b
❖ Precedence Summary:
Below table lists the precedence of all operators defined by C.
Note: All operators, except the unary operators and ?, associate from left to right. The
unary operators (*, &, –) and ? associate from right to left.
BIT, Bengaluru-04 42
1BEIT105
❖ TYPE CONVERSION
• In C language, the programmer can instruct the compiler to convert the data from one
data type to another data type. Sometimes, the compiler itself will convert the data from
1 data type to another data type this process of converting the data from one data type
to another data type is called as type conversion.
• It occurs when mixed data occurs.
• Type conversion is performed by a compiler.
• In type conversion, the destination data type can’t be smaller than the source data type.
• Generally, takes place when in an expression more than one data type is present. In
such conditions type conversion (type promotion) takes place to avoid loss of data.
BIT, Bengaluru-04 43
1BEIT105
Figure 2.2 shows the type conversion example: First, the character ch is converted to an
integer. Then the outcome of ch/i is converted to a double because f*d is double. The
outcome of f+i is float, because f is a float. The final result is double
BIT, Bengaluru-04 44
1BEIT105
• The programmer can instruct the compiler to change the type of the operand from one data
type to another data type.
• This forcible conversion from one data type to another data type is called as explicit type
conversion or casts
• In typing casting, a data type is converted into another data type by the programmer using
the casting operator during the program design
• The general form of a cast is:
(type) expression
Where,
• type is a valid data type.
• expression can be an operand such as variables or a constant.
Example:
i = (int)8.999 //8.999 is truncated to 8 and is stored in i. So, i=8
i =(int)5.99 / (int)2.4 //5.99 is truncated to 5 and 2.4 is truncated to 2 which results in 5/2=2
So, i=2
(float) x/2 // expression x/2 to evaluate to type float
BIT, Bengaluru-04 45
1BEIT105
Example program:
#include <stdio.h>
int main() {
int a = 9, b = 4;
float x = 3.5;
double result;
// Expression combining int, float, and double with explicit conversions
result = (double)a / b + (int)x * 2.0 + (float)(a + b) / 3;
printf("Result = %.2lf\n", result);
return 0;
}
Output:
Result = 12.58
In this program, explicit type conversions are used to control how different data types (int,
float, and double) interact in a complex expression, ensuring accurate arithmetic results and
preventing unwanted integer division.
❖ Expressions:
Examples of Expressions Using the Precedence Chart
If we have the following variable declarations:
int a = 0, b = 1, c = –1;
float x = 2.5, y = 0.0;
then,
(a) a && b = 0 (h) (x > y) + !a || c++
(b) a < b && c < b = 1 = ((x > y) + (!a)) || (c++)
(c) b + c || ! a = (1 + 1) || 0
= ( b + c) || (!a) =1
= 0 ||1 (i) a += b - = c *= 10
=1 a = a + (b = (b – (c = c * 10))
(d) x * 5 && 5 || ( b / c) a = a + (b = 1 – (-10))
= ((x * 5) && 5) || (b / c) a = a + (b = 11)
= (12.5 && 5) || (1/–1) a = 0 + 11
=1 a = 11
(e) a <= 10 && x >= 1 && b (j) –a * (5 + b) / 2 – c++ * b
= ((a <= 10) && (x >= 1)) && b = --a * 6 / 2 – c++ * b
= (1 && 1) && 1 = -1 * 6 / 2 – (-1) * 1
=1 = -1 * 3 – (-1)
(f) !x || !c || b + c = -2
= ((!x) || (!c)) || (b + c) (k) a * b * c
= (0 || 0) || 0 = (a * b) * c
=0 =0
(g) x * y < a + b || c (l) e = 3 * 4 + 5 * 6 → e = 42
= ((x * y) < (a + b)) || c (m) e = 3 * (4 + 5) * 6 → e = 162
= (0 < 1) || –1 → 1 (n) e = 3 * (4 % 5) / 2 → e = 6
(o) e = 3 * 4 % (5 / 2) → e = 0
BIT, Bengaluru-04 46