You are on page 1of 19

Unit – II

OPERATORS

An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions. Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are
called operands and + is called operator. C language supports following type of operators.

Types of Operators-

 Arithmetic Operators
 Logical (or Relational) Operators
 Bitwise Operators
 Assignment Operators
 Misc Operators

Arithmetic Operators:

 There are following arithmetic operators supported by C language: Assume variable


A holds 10 and variable B holds 20 then:

Operator Description Example

+ Adds two operands A + B will give 30

Subtracts second operand from the


- A - B will give -10
first

* Multiply both operands A * B will give 200

/ Divide numerator by denumerator B / A will give 2

Modulus Operator and remainder of


% B % A will give 0
after an integer division

Increment operator, increases


++ A++ will give 11
integer value by one

Decrement operator, decreases


-- A-- will give 9
integer value by one

Logical (or Relational) Operators:


There are following logical operators supported by C language

Assume variable A holds 10 and variable B holds 20 then


Operator Description Example

Checks if the value of two operands is


== equal or not, if yes then condition (A == B) is not true.
becomes true.

Checks if the value of two operands is


!= equal or not, if values are not equal (A != B) is true.
then condition becomes true.

Checks if the value of left operand is


> greater than the value of right operand, (A > B) is not true.
if yes then condition becomes true.

Checks if the value of left operand is


< less than the value of right operand, if (A < B) is true.
yes then condition becomes true.

Checks if the value of left operand is


greater than or equal to the value of
>= (A >= B) is not true.
right operand, if yes then condition
becomes true.

Checks if the value of left operand is


less than or equal to the value of right
<= (A <= B) is true.
operand, if yes then condition becomes
true.

Called Logical AND operator. If both


&& the operands are non zero then then (A && B) is true.
condition becomes true.

Called Logical OR Operator. If any of


|| the two operands is non zero then then (A || B) is true.
condition becomes true.

Called Logical NOT Operator. Use to


reverses the logical state of its operand.
! !(A && B) is false.
If a condition is true then Logical NOT
operator will make false.

Bitwise Operators:

Bitwise operator works on bits and perform bit by bit operation.

Assume if A = 60; and B = 13; Now in binary format they will be as follows:
A = 0011 1100

B = 0000 1101

-----------------

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A = 1100 0011

There are following Bitwise operators supported by C language


Operator Description Example

Binary AND Operator copies a bit to the


& (A & B) will give 12 which is 0000 1100
result if it exists in both operands.

Binary OR Operator copies a bit if it


| (A | B) will give 61 which is 0011 1101
exists in eather operand.

Binary XOR Operator copies the bit if it


^ (A ^ B) will give 49 which is 0011 0001
is set in one operand but not both.

Binary Ones Complement Operator is


~ (~A ) will give -60 which is 1100 0011
unary and has the efect of 'flipping' bits.

Binary Left Shift Operator. The left


operands value is moved left by the
<< A << 2 will give 240 which is 1111 0000
number of bits specified by the right
operand.

Binary Right Shift Operator. The left


operands value is moved right by the
>> A >> 2 will give 15 which is 0000 1111
number of bits specified by the right
operand.

Assignment Operators:

There are following assignment operators supported by C language:

Operator Description Example

= Simple assignment operator, C = A + B will assigne value of A + B into C


Assigns values from right side
operands to left side operand

Add AND assignment operator, It


adds right operand to the left
+= C += A is equivalent to C = C + A
operand and assign the result to left
operand

Subtract AND assignment operator,


It subtracts right operand from the
-= C -= A is equivalent to C = C - A
left operand and assign the result to
left operand

Multiply AND assignment operator,


It multiplies right operand with the
*= C *= A is equivalent to C = C * A
left operand and assign the result to
left operand

Divide AND assignment operator, It


divides left operand with the right
/= C /= A is equivalent to C = C / A
operand and assign the result to left
operand

Modulus AND assignment operator,


It takes modulus using two
%= C %= A is equivalent to C = C % A
operands and assign the result to
left operand

<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2

Right shift AND assignment


>>= C >>= 2 is same as C = C >> 2
operator

&= Bitwise AND assignment operator C &= 2 is same as C = C & 2

bitwise exclusive OR and


^= C ^= 2 is same as C = C ^ 2
assignment operator

bitwise inclusive OR and


|= C |= 2 is same as C = C | 2
assignment operator

Short Notes on L-VALUE and R-VALUE:

x = 1; takes the value on the right (e.g. 1) and puts it in the memory referenced by x. Here x and
1 are known as L-VALUES and R-VALUES respectively L-values can be on either side of the
assignment operator where as R-values only appear on the right.

So x is an L-value because it can appear on the left as we've just seen, or on the right like this: y
= x; However, constants like 1 are R-values because 1 could appear on the right, but 1 = x; is
invalid.
Misc Operators

There are few other operators supported by C Language.

Show Examples
Operator Description Example

sizeof() Returns the size of an variable. sizeof(a), where a is interger, will return 4.

& Returns the address of an variable. &a; will give actaul address of the variable.

* Pointer to a variable. *a; will pointer to a variable.

If Condition is true ? Then value X :


?: Conditional Expression
Otherwise value Y

Operators Categories:

All the operators we have discussed above can be categorized into following categories:

 Postfix operators, which follow a single operand.


 Unary prefix operators, which precede a single operand.
 Binary operators, which take two operands and perform a variety of arithmetic and
logical operations.
 The conditional operator (a ternary operator), which takes three operands and evaluates
either the second or third expression, depending on the evaluation of the first expression.
 Assignment operators, which assign a value to a variable.
 The comma operator, which guarantees left-to-right evaluation of comma-separated
expressions.

Precedence of C Operators:

Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example,
the multiplication operator has higher precedence than the addition operator:

For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher
precedenace than + so it first get multiplied with 3*2 and then adds into 7.

Here operators with the highest precede nce appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Category Operator Associativity

Postfix () [] -> . ++ - - Left to right


Unary + - ! ~ ++ - - (type) * & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left

Comma , Left to right

Expression

In programming, an expression is any legal combination of symbols that represents a value.

1. C Programming provides its own rules of Expression, whether it is legal expression or


illegal expression. For example, in the C language x+5 is a legal expression.
2. Every expression consists of at least one operand and can have one or more operators.
3. Operands are values and Operators are symbols that represent particular actions.

Statement-
A statement is a command given to the computer that instructs the computer to take a specific
action, such as display to the screen, or collect input. A computer program is made up of a series
of statements.

Contents-

 1 Labeled Statements
 2 Compound Statements
 3 Expression Statements
 4 Selection Statements
 5 Iteration Statements
 6 Jump Statements

printf ("Hi there!");


printf ("Hi there!");
printf ("Strange things are afoot...");

In C, a statement can be any of the following:

Labeled Statements

A statement can be preceded by a label. Three types of labels exist in C.

A simple identifier followed by a colon (:) is a label. Usually, this label is the target of a goto
statement.

Within switch statements, case and default labeled statements exist. A statement of the form

case constant-expression : statement

indicates that control will pass to this statement if the value of the control expression of the
switch statement matches the value of the constant-expression. A statement of the form

default : statement

indicates that control will pass to this statement if the control expression of the switch statement
does not match any of the constant-expressions within the switch statement. If the default
statement is omitted, the control will pass to the statement following the switch statement.

Compound Statements

A compound statement is the way C groups multiple statements into a single statement. It
consists of multiple statements and declarations within braces (i.e. { and }). In the ANSI C
Standard of 1989-1990, a compound statement contained an optional list of declarations
followed by an optional list of statements; in more recent revisions of the Standard, declarations
and statements can be freely interwoven through the code. The body of a function is also a
compound statement by rule.

Expression Statements

An expression statement consists of an optional expression followed by a semicolon (;). If the


expression is present, the statement may have a value. If no expression is present, the statement
is often called the null statement.
The printf function calls are expressions, so the statements above are expression statements.

Selection Statements

Three types of selection statements exist in C:

if ( expression ) statement

In this type of if-statement, the sub-statement will only be executed iff the expression is non-
zero.

if ( expression ) statement else statement

In this type of if-statement, the first sub-statement will only be executed iff the expression is
non-zero; otherwise, the second sub-statement will be executed. Each else matches up with the
closest unmatched if, so that the following two snippets of code are not equal:
if (expression)
if (secondexpression) statement1;
else
statement2;
if (expression)
{
if (secondexpression) statement1;
}
else
statement2;

because in the first, the else statement matches up with the if statement that has secondexpression
for a control, but in the second, the braces force the else to match up with the if that has
expression for a control.

Switch statements are also a type of selection statement. They have the format

switch ( expression ) statement

The statement here is usually compound and it contains case-labeled statements and optionally a
default-labeled statement.

Iteration Statements

C has three kinds of iteration statements. The first is a while-statement with the form

while ( expression ) statement

The substatement of a while runs repeatedly as long as the control expression evaluates to non-
zero at the beginning of each iteration. If the control expression evaluates to zero the first time
through, the substatement may not run at all.
The second is a do-while statement of the form

do statement while ( expression ) ;

This is similar to a while loop, except that the controlling expression is evaluated at the end of
the loop instead of the beginning and consequently the sub-statement must execute at least once.

The third type of iteration statement is the for-statement. In ANSI C 1989, it has the form

for ( expressionopt ; expressionopt ; expressionopt ) statement

In more recent versions of the C standard, a declaration can substitute for the first expression.
The opt subscript indicates that the expression is optional.

The statement
for (e1; e2; e3)
s;

is the rough equivalent of


{
e1;
while (e2)
{
s;
e3;
}
}

except for the behavior of continue statements within s.

The e1 expression represents an initial condition; e2 a control expression; and e3 what to happen
on each iteration of the loop. If e2 is missing, the expression is considered to be non-zero on
every iteration, and only a break statement within s (or a call to a non-returning function such as
exit or abort) will end the loop.

Jump Statements

C has four types of jump statements. The first, the goto statement, is used sparingly and has the
form

goto identifier ;

This statement transfers control flow to the statement labeled within the given identifier.

The second, the break statement, with the form

break ;
is used within iteration statements and switch statements to pass control flow to the statement
following the while, do-while, for, or switch.

The third, the continue statement, with the form

continue ;

is used within the substatement of interation statements to transfer control flow to the place just
before the end of the substatement. In for statements the iteration expression will then be
executed before the controlling expression is evaluated.

The fourth type of jump statement is the return statement with the form

return expressionopt ;

This statement returns from the function. If the function return type is void, the function may not
return a value; otherwise, the expression represents the value to be returned.

Console based I/O and related built in I/O function-

Input : In any programming language input means to feed some data into program. This can be
given in the form of file or from command line. C programming language provides a set of built-
in functions to read given input and feed it to the program as per requirement.

Output : In any programming language output means to display some data on screen, printer or
in any file. C programming language provides a set of built-in functions to output required data.

Here we will discuss only one input function and one putput function just to understand the
meaning of input and output. Rest of the functions are given into C - Built-in Functions

printf() function

This is one of the most frequently used functions in C for output. ( we will discuss what is
function in subsequent chapter. ).

Try following program to understand printf() function.


#include <stdio.h>

main()
{
int dec = 5;
char str[] = "abc";
char ch = 's';
float pi = 3.14;

printf("%d %s %f %c\n", dec, str, pi, ch);


}
The output of the above would be:
5 abc 3.140000 c

Here %d is being used to print an integer, %s is being usedto print a string, %f is being used to
print a float and %c is being used to print a character.

scanf() function

This is the function which can be used to to read an input from the command line.

Try following program to understand scanf() function.


#include <stdio.h>

main()
{
int x;
int args;

printf("Enter an integer: ");


if (( args = scanf("%d", &x)) == 0) {
printf("Error: not an integer\n");
} else {
printf("Read in %d\n", x);
}
}

Here %d is being used to read an integer value and we are passing &x to store the vale read
input. Here &indicates the address of variavle x.

This program will prompt you to enter a value. Whatever value you will enter at command
prompt that will be output at the screen using printf() function. If you eneter a non-integer value then it
will display an error message.
Enter an integer: 20
Read in 20

getch()
The getch() function is used to catch a character from the keyboard. The getch() function reads a
single character from the keyboard but does not show on the screen. For this functionality, you
can use the getch() function to hold the output window until hitting any key from the keyboard.
#include <conio.h>
#include <stdio.h>

void main()
{
int c;
clrscr();
printf(“Press any key\n”);
c = getch();
if (c)
printf(“A key is pressed from keyboard ”);
else
printf(“An error occurred ”);
getch();
}

Function : getchar()
getchar() is used to get or read the input (i.e a single character) at run time.

Declaration:
int getchar(void);

Example Declaration:
char ch;
ch = getchar();
Return Value:
This function return the character read from the keyboard.

Example Program:
void main()
{

char ch;
ch = getchar();
printf("Input Char Is :%c",ch);

}
Program Explanation:
Here, declare the variable ch as char data type, and then get a value through getchar()library
function and store it in the variable Ch. And then, print the value of variable ch.
During the program execution, a single character is get or read through the getchar(). The given
value is displayed on the screen and the compiler wait for another character to be typed. If you
press the enter key/any other characters and then only the given character is printed through
the printf function.

putchar()
putchar() displays any alphanumeric characters to the standard output device. It displays only
one character at a time.
Declaration:
int putch(variable_name);
Example Declaration:
char ch = 'a';
putchar(ch);
Remarks:
putchar displays one character at a time to the Monitor.
Example Program:
void main()
{
char ch='a';
putchar(ch);
}

Concept of Header Files-


Header files contain definitions of functions and variables which can be incorporated into any C
program by using the pre-processor #include statement. Standard header files are provided with
each compiler, and cover a range of areas, string handling, mathematical, data conversion,
printing and reading of variables.

To use any of the standard functions, the appropriate header file should be included. This is done
at the beginning of the C source file. For example, to use the function printf() in a program, the
line

#include <stdio.h>

should be at the beginning of the source file, because the definition for printf() is found in the file
stdio.h All header files have the extension .h and generally reside in the /include subdirectory.

#include <stdio.h>
#include "mydecls.h"
The use of angle brackets <> informs the compiler to search the compilers include directory for
the specified file. The use of the double quotes "" around the filename inform the compiler to
search in the current directory for the specified file.

A header file is a file with extension .h which contains C function declarations and macro
definitions to be shared between several source files. There are two types of header files: the files
that the programmer writes and the files that comes with your compiler.

You request to use a header file in your program by including it with the C preprocessing
directive #include, like you have seen inclusion of stdio.h header file, which comes along with
your compiler.

Including a header file is equal to copying the content of the header file but we do not do it
because it will be error-prone and it is not a good idea to copy the content of a header file in the
source files, especially if we have multiple source files in a program.

A simple practice in C or C++ programs is that we keep all the constants, macros, system wide
global variables, and function prototypes in the header files and include that header file wherever
it is required.
Include Syntax

Both the user and the system header files are included using the preprocessing directive #include.
It has the following two forms −

#include <file>

This form is used for system header files. It searches for a file named 'file' in a standard list of
system directories. You can prepend directories to this list with the -I option while compiling
your source code.

#include "file"

This form is used for header files of your own program. It searches for a file named 'file' in the
directory containing the current file. You can prepend directories to this list with the -I option
while compiling your source code.
Include Operation

The #include directive works by directing the C preprocessor to scan the specified file as input
before continuing with the rest of the current source file. The output from the preprocessor
contains the output already generated, followed by the output resulting from the included file,
followed by the output that comes from the text after the #include directive. For example, if you
have a header file header.h as follows −

char *test (void);

and a main program called program.c that uses the header file, like this −

int x;
#include "header.h"

int main (void) {


puts (test ());
}

the compiler will see the same token stream as it would if program.c read.

int x;
char *test (void);

int main (void) {


puts (test ());
}

Once-Only Headers

If a header file happens to be included twice, the compiler will process its contents twice and it
will result in an error. The standard way to prevent this is to enclose the entire real contents of
the file in a conditional, like this −

#ifndef HEADER_FILE
#define HEADER_FILE

the entire header file file

#endif

This construct is commonly known as a wrapper #ifndef. When the header is included again, the
conditional will be false, because HEADER_FILE is defined. The preprocessor will skip over
the entire contents of the file, and the compiler will not see it twice.
Computed Includes

Sometimes it is necessary to select one of the several different header files to be included into
your program. For instance, they might specify configuration parameters to be used on different
sorts of operating systems. You could do this with a series of conditionals as follows −

#if SYSTEM_1
# include "system_1.h"
#elif SYSTEM_2
# include "system_2.h"
#elif SYSTEM_3
...
#endif

But as it grows, it becomes tedious, instead the preprocessor offers the ability to use a macro for
the header name. This is called a computed include. Instead of writing a header name as the
direct argument of #include, you simply put a macro name there −
#define SYSTEM_H "system_1.h"
...
#include SYSTEM_H

SYSTEM_H will be expanded, and the preprocessor will look for system_1.h as if the #include
had been written that way originally. SYSTEM_H could be defined by your Makefile with a -D
option.

Preprocessor directives

The C Preprocessor is not a part of the compiler, but is a separate step in the compilation
process. In simple terms, a C Preprocessor is just a text substitution tool and it instructs the
compiler to do required pre-processing before the actual compilation. We'll refer to the C
Preprocessor as CPP.

All preprocessor commands begin with a hash symbol (#). It must be the first nonblank
character, and for readability, a preprocessor directive should begin in the first column. The
following section lists down all the important preprocessor directives −
Directive Description
#define Substitutes a preprocessor macro.
#include Inserts a particular header from another file.
#undef Undefines a preprocessor macro.
#ifdef Returns true if this macro is defined.
#ifndef Returns true if this macro is not defined.
#if Tests if a compile time condition is true.
#else The alternative for #if.
#elif #else and #if in one statement.
#endif Ends preprocessor conditional.
#error Prints error message on stderr.
#pragma Issues special commands to the compiler, using a standardized method.

Preprocessors Examples

Analyze the following examples to understand various directives.


#define MAX_ARRAY_LENGTH 20

This directive tells the CPP to replace instances of MAX_ARRAY_LENGTH with 20. Use
#define for constants to increase readability.
#include <stdio.h>
#include "myheader.h"
These directives tell the CPP to get stdio.h from System Libraries and add the text to the current
source file. The next line tells CPP to get myheader.h from the local directory and add the
content to the current source file.
#undef FILE_SIZE
#define FILE_SIZE 42

It tells the CPP to undefine existing FILE_SIZE and define it as 42.

Include Syntax

Both user and system header files are included using the preprocessing directive ‘#include’. It
has two variants:
#include <file>
This variant is used for system header files. It searches for a file named file in a standard
list of system directories. You can prepend directories to this list with the -I option (see
Invocation).
#include "file"
This variant is used for header files of your own program. It searches for a file named file
first in the directory containing the current file, then in the quote directories and then the
same directories used for <file>. You can prepend directories to the list of quote
directories with the -iquote option.

The argument of ‘#include’, whether delimited with quote marks or angle brackets, behaves like
a string constant in that comments are not recognized, and macro names are not expanded. Thus,
#include <x/*y> specifies inclusion of a system header file named x/*y.

However, if backslashes occur within file, they are considered ordinary text characters, not
escape characters. None of the character escape sequences appropriate to string constants in C
are processed. Thus, #include "x\n\\y" specifies a filename containing three backslashes. (Some
systems interpret ‘\’ as a pathname separator. All of these also interpret ‘/’ the same way. It is
most portable to use only ‘/’.)

It is an error if there is anything (other than comments) on the line after the file name.

If the file name that's enclosed in double quotation marks is an incomplete path
specification, the preprocessor first searches the "parent" file's directory. A parent file is the file
that contains the #include directive. For example, if you include a file named file2 in a file
named file1, file1 is the parent file.

Include files can be "nested"; that is, an #include directive can appear in a file that's named by
another #include directive. For example, file2 could include file3. In this case, file1 would still
be the parent of file2, but it would be the "grandparent" of file3.

When include files are nested and when compiling occurs on the command line, directory
searching begins with the directories of the parent file and then proceeds through the directories
of any grandparent files. That is, searching begins relative to the directory that contains the
source that's currently being processed. If the file is not found, the search moves to directories
that are specified by the /I compiler option. Finally, the directories that are specified by the
INCLUDE environment variable are searched.

From the development environment, the INCLUDE environment variable is ignored. For
information about how to set the directories that are searched for include files—this also applies
to the LIB environment variable—see VC++ Directories Property Page.

This example shows file inclusion by using angle brackets:


#include <stdio.h>

This example adds the contents of the file named STDIO.H to the source program. The angle
brackets cause the preprocessor to search the directories that are specified by the INCLUDE
environment variable for STDIO.H, after it searches directories that are specified by the /I
compiler option.
#define-

In the C Programming Language, the #define directive allows the definition of macros within
your source code. These macro definitions allow constant values to be declared for use
throughout your code.

Macro definitions are not variables and cannot be changed by your program code like variables.
You generally use this syntax when creating constants that represent numbers, strings or
expressions.

Syntax

The syntax for creating a constant using #define in the C language is:
#define CNAME value

OR
#define CNAME (expression)
CNAME
The name of the constant. Most C programmers define their constant names in uppercase,
but it is not a requirement of the C Language.
value
The value of the constant.
expression
Expression whose value is assigned to the constant. The expression must be enclosed in
parentheses if it contains operators.

Note

 Do NOT put a semicolon character at the end of #define statements. This is a common
mistake.

Example
Let's look at how to use #define directives with numbers, strings, and expressions.

Number

The following is an example of how you use the #define directive to define a numeric constant:
#define AGE 10

In this example, the constant named AGE would contain the value of 10.

String

You can use the #define directive to define a string constant.

For example:
#define NAME "TechOnTheNet.com"

In this example, the constant called NAME would contain the value of "TechOnTheNet.com".

Below is an example C program where we define these two constants:


#include <stdio.h>

#define NAME "TechOnTheNet.com"


#define AGE 10

int main()
{
printf("%s is over %d years old.\n", NAME, AGE);
return 0;
}

Important / Practice Question

Q:1 Define Operator. Explain various types of operator based upon the number of operands.
Q:2 What are arithmetic and logical operators?
Q:3 Write Short Note on Preprocessor Directive
 # define
 #include
Q:4 What is Swapping? Write a C program to swap 2 variables without using third variable.
Q:5 Differentiate among getch(), getche(), getchar() functions.
Q:6 Explain the use of goto and exit statements.
Q:7 What are header file? Also explain pre-processor directives in c with examples.

You might also like