Anda di halaman 1dari 21

C Operators Notes

The Int Types


An int was originally intended to be the "natural" word size of the processor. Many modern processors can handle different word sizes with equal ease. It is int which causes the greatest confusion. Some people are certain that an int has 16 bits and sizeof(int) is 2. Others are equally sure that an int has 32 bits and sizeof(int) is 4. Who is right? On any given compiler, one or the other could be right. On some compilers, both would be wrong. I know of one compiler for a 24 bit DSP where an int has 24 bits. The actual range of values which the signed and unsigned int types can hold are: A signed int can hold all the values between INT_MIN and INT_MAX inclusive. INT_MIN is required to be -32767 or less, INT_MAX must be at least 32767. Again, many 2's complement implementations will define INT_MIN to be -32768 but this is not required. An unsigned int can hold all the values between 0 and UINT_MAX inclusive. UINT_MAX must be at least 65535. The int types must contain at least 16 bits to hold the required range of values.

NOTE:

The required ranges for signed and unsigned int are identical to those for signed and unsigned short. On compilers for 8 and 16 bit processors (including Intel x86 processors executing in 16 bit mode, such as under MS-DOS), an int is usually 16 bits and has exactly the same representation as a short. On compilers for 32 bit and larger processors (including Intel x86 processors executing in 32 bit mode, such as Win32 or Linux) an int is usually 32 bits long and has exactly the same representation as a long.

The Short Int Types


There are two types of short int, signed and unsigned. If neither is specified the short is signed. The "int" in the declaration is optional. All 6 of the following declarations are correct: short x; x is a signed short int short int x; signed short x; signed short int x; unsigned short x; unsigned short int x; The range of the short int types: x is a signed short int x is a signed short int x is a signed short int x is an unsigned short int x is an unsigned short int

JNTUWORLD

C Operators Notes A signed short can hold all the values between SHRT_MIN and SHRT_MAX inclusive. SHRT_MIN is required to be -32767 or less, SHRT_MAX must be at least 32767. Again, many 2's complement implementations will define SHRT_MIN to be -32768 but this is not required. An unsigned short can hold all the values between 0 and USHRT_MAX inclusive. USHRT_MAX must be at least 65535. The short types must contain at least 16 bits to hold the required range of values. On many (but not all) C implementations, a short is smaller than an int. Programs which need to have very large arrays of integer values in memory, or store very large numbers of integers in files might save memory or storage space by using short in place of int if both of the conditions below are met: 1. Short is truly smaller than int on the implementation. 2. All of the required values can fit into a short. NOTE: On some processor architectures code to manipulate shorts can be larger and slower than corresponding code which deals with ints. This is particularly true on the Intel x86 processors executing 32 bit code, as in programs for Windows (NT/95/98), Linux, and other UNIX derivatives. Every instruction which references a short in such code is one byte larger and usually takes extra processor time to execute.

The Long Int Types


There are two types of long int, signed and unsigned. If neither is specified the long is signed. The "int" in the declaration is optional. All 6 of the following declarations are correct: long x; x is a signed long int long int x; signed long x; signed long int x; unsigned long x; unsigned long int x; The range of the long int types: A signed long can hold all the values between LONG_MIN and LONG_MAX inclusive. LONG_MIN is required to be -2147483647 or less, LONG_MAX must be at least 2147483647. Again, many 2's complement implementations will define LONG_MIN to be -2147483648 but this is not required. x is a signed long int x is a signed long int x is a signed long int x is an unsigned long int x is an unsigned long int

JNTUWORLD

C Operators Notes An unsigned long can hold all the values between 0 and ULONG_MAX inclusive. ULONG_MAX must be at least 4294967295. The long types must contain at least 32 bits to hold the required range of values.

The Long Long Int Types (C Only)


64 bit processors have been readily available in workstations for several years, and they will be coming to desktop computers soon. These processors can address enough memory to have arrays with more elements than a 32 bit long can specify. Inexpensive disk drives in use today can hold a file which contains more bytes than a 32 bit offset can reach. The requirement for an integer type required to hold more than 32 bits is obvious. The 1999 update to the ANSI/ISO C language standard has added a new integer type to C, one that is required to be at contain at least 64 bits. Included in this update are the new variable types signed and unsigned long long . The selected name comes from gcc and several other compilers which already provide this type as an extension. On 32 bit Windows compilers from Microsoft, Borland (and maybe others) this same extension has the name __int64. While the C++ standard is quite new and most likely will not change for several years, it is almost certain that C++ compilers will add support for these types as well. The C++ compilers which come with the implementations mentioned above do. There are two types of long long int, signed and unsigned. If neither is specified the long long is signed. The "int" in the declaration is optional. All 6 of the following declarations are correct: long long x; long long int x; signed long long x; signed long long int x; unsigned long long x; unsigned long long int x; The range of the long long int types: A signed long long can hold all the values between LLONG_MIN and LLONG_MAX inclusive. LLONG_MIN is required to be -9223372036854775807 or less, LLONG_MAX must be at least 9223372036854775807. Again, many 2's complement implementations will define LLONG_MIN to be -9223372036854775808 but this is not required. x is a signed long long int x is a signed long long int x is a signed long long int x is a signed long long int x is an unsigned long long int x is an unsigned long long int

JNTUWORLD

C Operators Notes An unsigned long long can hold all the values between 0 and ULLONG_MAX inclusive. ULLONG_MAX must be at least 18446744073709551615. The long types must contain at least 64 bits to hold the required range of values.

Values In <limits.h>
The standard header <limits.h> contains macros which expand to values which allow a program to determine information about the ranges of values each integer type can hold at run time. Each of these types (except for "plain" char, that is char without a signed or unsigned in front of it) must be able to contain a minimum range of values. Type signed char <limits.h> Constant SCHAR_MIN SCHAR_MAX Minimum Value -127 127 0 255 (note 1) -32767 32767 0 65535 -32767 32767 0 65535 -2147483647 2147483647 0 4294967295 -9223372036854775807 9223372036854775807

unsigned char

UCHAR_MAX CHAR_MIN CHAR_MAX SHRT_MIN SHRT_MAX

"plain" char

signed short

unsigned short

USHRT_MAX INT_MIN INT_MAX

signed int

unsigned int

UINT_MAX LONG_MIN LONG_MAX

signed long

unsigned long

ULONG_MAX LLONG_MIN LLONG_MAX

signed long long

JNTUWORLD

C Operators Notes

unsigned long long

ULLONG_MAX

0 18446744073709551615

Note 1: On implementations where default " plain" is signed, CHAR_MIN is equal to SCHAR_MIN and CHAR_MAX is equal to SCHAR_MAX. If "plain" char is unsigned, CHAR_MIN is 0 and CHAR_MAX is equal to UCHAR_MAX.

OPERATORS:
C includes a large number of operators which fall into different categories. These are Arithmetic Operators Relational Operators Logical Operators Assignment Operators Unary Operators Conditional Operators Bit-Wise Operators Arithmetic Operators: To solve most programming problems we need to perform arithmetic operations by writing arithmetic expressions. The following table shows all arithmetic operators provided by C. Arithmetic Meaning Declarations: int a=5, b=16 Operators Double c=3.0, d=7.5 Integer Examples Floating Point Examples + _ * / % Addition Subtraction Multiplication Division Remainder (Modulo Division) a + b is 21 a b is -11 b a is 11 b * a is 80 a / b is 5 b / a is 3 a % b is 5 b % a is 1 c + d is 10.5 c - d is -4.5 d c is 4.5 c * d is 22.5 c / d is 0.4 d / c is 2.5 Not Possible

Each operator manipulates two operands, which may be constants, variables, or other arithmetic expression. The arithmetic operators may be used with int or double data type 5 JNTUWORLD

C Operators Notes operands. On the other hand, the remainder operator also known as modulus operator can be used with integer operands to find the remainder of the division. When both operands in an arithmetic expression are integers, the expression is called as integer expression, and the operation is called integer arithmetic. When both operands in an arithmetic expression are floating point numbers, the expression is called floating point expression or real expression, and the operation is called floating point arithmetic or real arithmetic. The result of an integer arithmetic always have integer value. The remainder operator (%) requires that both operands be integers and the second operand be non zero. The division operator requires the second operand be nonzero. The result of integer division results in a truncated quotient (i.e. the decimal portion of the quotient will be dropped). If a division operation is carried out with two floating point numbers or with one floating point number and one integer, the result will be a floating point quotient. For example 7.5/5=1.5. If one of both operands are negative then the addition, subtraction, multiplication, and division operations will result in values whose signs are determined by the usual rules of algebra. The result of the remainder operation always gets the sign of first operand. For examples If a=14 and b=5 then a % b=4 If a=-14 and b=5 then a % b = -4 If a = -14 and b = 5 then a % b = -4 If a= -14 and b = -5 then a % b = 4 Operands the differ in type may undergo type conversion before the expression takes on its final value. In general, the final result will be expressed in the highest precision possible, consistent with the data type of the operands.

For example Operand 1 Short Int Double Double Operand 2 Int Float Float Int Result Int Float Double Double

JNTUWORLD

C Operators Notes Int Long Long

Relational Operators:
Relational Operators are used in C to compare values, typically in conditional control statements. The four relational operators in c are <,<=,>,>=. There are two equality operators = = and !=. They are closely associated with the relational operators. Relational Operator < <= > >= Equality Operators == != Meaning Less than Less than or equal to Greater than Greater than or equal to Meaning Equal to Not equal to

The double equal sign = = used to compare equality is different from the single equal to = sign which is used as an assignment operator. These six operators are used to form logical expressions, which represent conditions that are either true or false. The result of the expressions is of type integer, since true is represented by the integer value 1 and false is represented by the value 0. Declarations: Expression i< 4 (i + j <= 10 f >g f <= g j/i != 2 int i=3, j=7; flaot f=5.5,g=4.5 Interpretation True True True False False

Value 1 1 1 0 0

Among the relational and equality operators each operator is a complement of another operator in group.

JNTUWORLD

C Operators Notes Using complement operators we can simplify the expressions as Original Expression !(a<b) !(a>b) !(a!=b) !(a<=b) !(a>=b) !(a= =b) Logical Operators: In addition to arithmetic and relational operators, C has 3 logical operators for combining logical values and creating new logical values. These operators are Logical Operator Meaning ! NOT && Logical AND || Logical OR NOT: The NOT operator (!) is a unary operator (Operator that acts upon single operand). It changes a true value (1) to false (zero) and a false value to true. AND: The AND operator (&&) is a binary operator. Its result is true only when both operands are true; otherwise it is false. OR: The OR operator (| |) is a binary operator. Its result is false only when both the operands are false; otherwise true. Declarations: int i=3, j=7; double f=5.5 , g=4.5 char ch=T Expression Interpretation Value (i<= 5) && (ch = = T) True 1 (j < 8) || (ch = = L) True 1 (f + g) = = 10.0 | | I < 2 F >= 6 | | (i*j)<15 !(f>5.0) True False False 1 0 0 Simplified Expression a>=b a<=b a= =b a>b a<b a!=b

Assignment Operator:
Assignment operator assigns the value of expression on the right side of it to the variable on the left of it. The assignment expression evaluates the operand on the right side of the 8 JNTUWORLD

C Operators Notes operator (=) and places its value in the variable on the left. Assignment expressions that make use of assignment operator have the form: Identifier = expression; Where identifier represents a variable and expression represents a constant, a variable or a more complex expression. Ex: a = 2; Area = length * width; Note: If the two operands in an assignment expression are of different data types, then the value of the expression on the right side of assignment operator will automatically be converted to the type of the identifier on the left of assignment operator.

For example A floating value may be truncated if it is assigned to an integer identifier. A double value may be rounded if it is assigned to a floating point identifier. An integer value may be changed if it is assigned to a short integer identifier or to a character identifier.

Unary Operators:
The operators that act upon a single operand to produce a new value are known as unary operators. C supports the following unary operators. Operators: Minus operator Increment operator ++ Decrement operator - Size operator (type) operator

Minus operator
The most common unary operation is a unary minus, where a numerical constant, variable or expression is preceded by a minus sign. It is important to note that the unary minus operation is distinctly different from the arithmetic operator which denotes subtraction (-). The subtraction operator requires two separate operands. Ex: -123, -qty, -4E-8

JNTUWORLD

C Operators Notes

Increment and Decrement Operator


The increment operator (++) adds 1 to the operand, whereas the decrement operator (--) subtract 1 from the operand. The increment and decrement operators can each be used in two different ways, depending on whether the operator is written before or after the operand. For example a++; /* operator is written after the operand */ ++a; /* operator is written before the operand */ If the operator precedes the operand (e.g., ++a), then it is called pre-increment operator and the operand will be changed in value before it is used for its intended purpose within the program. On the other hand, if the operator follows the operand (i.e a++), then it is called post-increment operator and the value of the operand will be changed after it is used.

sizeof Operator:
In C, an operator sizeof is used to calculate size of various datatypes. These can be basic or primitive datatypes present in the language, as well as the ones, created by programmer. The sizeof opearator looks like a function, but it is actually an operator that returns the length, in bytes. It is used to get size of space any data-element/datatype occupies in memory. If type name is used, it always needs to be enclosed in parentheses, whereas variable name can be specified with or without parentheses. Ex: int i; sizeof i; sizeof(int);

Type Conversion (Cast Operator)


Rather than let the compiler implicitly convert data, we can convert data from one type to another by using cast operator. To cast data from one type to another it is necessary to specify type in parentheses before the value we want to be converted. For example to convert integer variable count, to a float we code the expression as (float) count; Since cast operator is an unary operator, we must put binary expression to be casted in parentheses to get the correct conversion. For example (float) (a+b) One use of the cast is to ensure that the result of a division is a floating point number. In case of division, proper casting is necessary.

10

JNTUWORLD

C Operators Notes

Conditional Expressions
Simple conditional operations can be carried out with the conditional operator (? :). The conditional operator (? :) is a ternary operator since it takes three operands. The general form of conditional expression is Test expression ? expression 1 : expression 2; Conditional operator works as follows: The test expression is implicitly converted to Boolean expression. It is evaluated. If the result of test expression is true(1), the expression 1 is evaluated and the conditional expression takes on value of expression 1. If the result of test expression is false (0), the expression 2 is evaluated and the conditional expression takes on value of expression 2.

Therefore the result of the conditional operator is the result of whichever expression is evaluated the first or the second. Only on of the last 2 expressions is evaluated in a conditional expression.

Bitwise operators
The bitwise operators are the bit manipulation operators. They can manipulate individual bits within the piece of data. These operators can operate on integers and characters but not on floating point numbers or numbers having double data type. Operator Description The bitwise complement operator is an unary operator. It complements each bit of the operand. The bitwise AND operator compares each bit of its first operand to the corresponding bit of its second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise the corresponding bit is set to 0. The bitwise inclusive OR operator compares each bit of its first operand to the corresponding bit of its second operand. If either of bits is 1 the corresponding result bit is set to 1, otherwise the corresponding bit is set to 0. Example Operand = 1111 0000 1111 0000 ~ operand Resulted Operand = 0000 1111 0000 1111 Operand 1 = 1111 1111 1111 0000 Operand 2 = 1111 0000 1111 0000 X= operand 1 & operand 2 Then X= 1111 0000 1111 0000 Operand 1= 0000 1111 0011 0000 Operand 2= 1111 1111 0000 1111 X=operand 1 | operand 2 Then X= 1111 1111 0011 1111

&

11

JNTUWORLD

C Operators Notes The bitwise exclusive OR operator compares each bit of its first operand to the corresponding bit of its second operand. If one bit is 0 and the other bit is 1 the corresponding result bit is set to 1 otherwise result bit is set to 0. The bitwise shift left operator is a binary operator. The first operand is the value to be shifted and the second operand specifies the number of bits to shifted. The bitwise right shift operator is a binary operator. The first operand is the value to be shifted and the second operand specifies the number of bits to be shifted. Operand 1= 1111 0000 1100 0011 Operand 2= 1111 1111 0011 0011 X= operand 1 ^ operand 2 Then X= 0000 1111 1111 0000 Operand 1 = 1111 0000 1111 0001 Operand 2 = 1 X=operand 1 << operand 2 X= 1110 0001 1110 0010 Operand 1 = 1111 0000 1111 0000 Operand 2 = 2 X = operand 1 >> operand 2 X=00 1111 0000 1111 00

<<

>>

Operator Precedence and Associativity


Operator precedence describes the order in which c evaluates different operators in a complex expression. For example, in the expression a = 4+b*2, which happens first, the addition or the multiplication? The operator precedence will tell us which operation should perform first. The operator which is having highest precedence will evaluate first and the operator which is having lowest precedence evaluate last. If two operators are on the same level of precedence then the order they will be evaluated in is going to be considered. This is knows as Associativity property of an operator. Operator Type Parentheses, Braces Operator () [] ++ -+ ! ~ Unary (type) & Size of Binary * / % + Description Parentheses Brackets Unary pre increment / pre decrement Unary plus / minus Unary Logical negation / bitwise complement Unary cast Address Determine Size in bytes Multiplication / Division/ Modules Addition / Subtraction Associativity Left to right Precedence Level 1

Right to left

Left to right Left to right

3 4

12

JNTUWORLD

C Operators Notes Bitwise shift left, bitwise shift right Relational less than / less than or equal to Relational greater than / greater than or equal to Relational is equal to / is not equal to Bitwise AND Bitwise XOR Bitwise OR Logical AND Logical OR Ternary (Conditional) Ternary ? : = += Assignment %= &= ^= != <<= >>= Comma , -= Assignment Addition/Subtraction Assignment Multiplication/Division Assignment Modulus/bitwise AND assignment Bitwise exclusive/inclusive OR assignment Bitwise Shift left/right assignment Comma (separate Expression) Right to left 13

<< >> < <= > >= = = != & ^ | && ||

Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right

5 6 7 8 9 10 11 12

*= /=

Right to left

14

Left to right

15

INPUT & OUTPUT STATEMENTS


Reading data, processing it and writing the processed data known as information or a result of a program are the essential functions of a program. The C is a functional language. It provides a number of macros and functions to enable the programmer to effectively carry out these input and output operations. Some of the input/output functions / macros in C are 1. getchar() 2. putchar() 3. scanf() 4. printf() 13 JNTUWORLD

C Operators Notes 5. gets() 6. puts()

The data entered by the user through the standard input device and processed data is displayed on the standard output device. I/O Functions: I / O functions are grouped into two categories. Unformatted I/O functions Formatted I/O function. The Formatted I/O functions allows programmers to specify the type of data and the way in which it should be read in or written out. On the other hand, unformatted I/O functions do not specify the type of data and the way is should be read or written. Amongst the above specified I/O functions scanf() and printf() are formatted I/O functions. Function Formatted Unformatted Input Output scanf() printf() getchar(),gets() putchar(),puts()

Formatted Output The printf function C provides the printf function to display the data on the monitor. This function can be used to display any combination of numerical values, single characters and strings. The general form of printf statement Function name Function arguments printf(my roll number is %d. \n, rollno) control string print list The %d is known as a placeholder or conversion character or format code or format specifier. At the time of display the value of the specified variable is substituted at the place of placeholder. In out example, value of rollno is substituted in place of %d. The printf uses different placeholders to display different type of data items.

Placeholder
%c %d

Type of Data Item displayed


Single character Signed decimal integer

14

JNTUWORLD

C Operators Notes %e %f %g %i %o %s %u %x Floating point number with an exponent Floating point number without an exponent Floating point number either with exponent or without exponent depending on value. Trailing zeros and trailing decimal point will not be displayed. Singed decimal number Octal number, without leading zero String Unsigned decimal integer Hexadecimal number, without leading zero

There are certain letters which may be used as prefix for certain placeholders. These are h: the h letter can be applied to d,i,o,u and x placeholders. The h letter tells printf() to display short integers. As an example, %hu indicates that the data is of type short unsigned integer. l: the l letter can be applied to d,i,o,u and x placeholder. The l letter tells printf() to display long integers. As an example, %ld indicates that the data is of type long integer. When it is applied to f, it indicates double data type. L: the L letter, when applied to f indicates long double data type. Some important points to remember Control string must be enclosed within the double quotes. For every data item to be displayed there must be a placeholder corresponding to its data type. Multiple placeholders are allowed in the control string. In such a case they may be contiguous or separated by blank spaces or commas. The data items must be included in the print list and they must be separated by commas. Print list is not enclosed within double quotes. The comma must be used to separate the format string and the print list.

Formatting integer output


We have seen that how integer numbers can be displayed on the monitor using %d placeholder. In case of integer numbers, the placeholder can accept modifiers to specify the minimum field width and left justification by default, all output is right

15

JNTUWORLD

C Operators Notes justified. We can force the information to be left justified by putting a minus sign directly after the %. For example

printf statement
1 2

Output (assume x=1234)


3 4

printf(%d,x);

printf(%6d,x);

1 Right justified

printf(%-6d,x);

Left justified As shown in the above examples, if the number width in digits is less than the minimum field width the empty places are filled with spaces. However if the number width is greater than the minimum field width, the number is printed in the full, overriding the minimum field width specification. This is illustrated in the following list. It is also possible to pad the empty places with zeros. If we want to pad with zeros, we have to place a zero before the minimum field width specifier.

printf statement
printf(%3d,x); 1 2

Output (assume x=1234)


3 4

printf(%06d,x);

Overriding the minimum field width 0 0 1 2 3 4 Padding with zeros

As shown in the above examples, if the number width in digits is less than the minimum field width the empty places are filled with spaces. However if the number width is greater than the minimum field width, the number is printed in the full, overriding the minimum field width specification. This is illustrated in the following list. It is also possible to pad the empty places with zeros. If we want to pad with zeros, we have to place a zero before the minimum field width specifier.

16

JNTUWORLD

C Operators Notes

printf statement
printf(%3d,x); 1 2

Output (assume x=1234)


3 4

Overriding the minimum field width 0 0 1 2 3 4 printf(%06d,x); Padding with zeros

Formatting floating point output


In case of floating point numbers placeholder can accept modifiers that specify the minimum field width, precision and left justification. To add a modifier we have to place a decimal point follower by the precision after the field width specifier. For e and f formats, the precision modifier determines the number of decimal places to be displayed. For example %8.4f will display a number at least 8 characters wide including decimal point with four decimal places.

printf statement
3

Output (assume x=3456.12065)


4 5 6 . 1 2 0 6 5 0

printf(%f,x);

Default precision is 6 3 4 5 6 . 1 2

printf(%7.2f,x);

Total 7 characters wide out of 2 are decimal point printf(%9.2f,x); 3 Right justified printf(%-9.2f,x); 3 4 5 6 . 1 2 4 5 6 . 1 2

left justified printf(%9.3e,x); 3 . 4 5 6 E + 0 3

3 decimal places and total 9 characters wide

Formatting String Output


17 JNTUWORLD

C Operators Notes

When the precision is applied to strings, the number preceding period specifies the minimum field width and the number following the period specifies the number of characters of the string to be displayed. For examples %16.9s will display a string that will be at least sixteen characters long; however only first nine characters from the string are displayed with remaining blank characters. Let us see the important points related to formatted string display. When minimum field width is specified without negative sign, display is right justified. When only minimum field width is specified and it is less than the actual string length, the minimum field width is overridden and complete string is displayed. We can insert negative sign before minimum field width to get left justified display.

printf statement
printf(%s,str);

Output (assume str: THIS IS A TEST STRING containing 21 characters including blanks.)
T H I S I S A T E S T S T R I N G

printf(%24s, str);

T HI S

I S

T ES T

S T R I NG

printf(%24.14s ,str);

T H I S

I S

T ES T

Escape Sequences to enhance the readability of output The backslash symbol( \ ) is known as escape character. Since the newline character and the tab character begin with backslash they are called escape sequences. They are

Escape Sequences
\n \t

Function
Newline : Displays the message or variable values following it on the next line. Tab: Moves cursor to the next tab

18

JNTUWORLD

C Operators Notes Backspace: Moves cursor one position to the left of its current position. Form feed: Advances the computer stationary attached to the printer to the top of next page. Single Quote: Displays single quote Backslash: Displays backslash Double Quote: Displays double quote Carriage Return : Takes the cursor to the beginning of the line in which it is currently placed. Alert: Alerts the user by sounding the speaker inside the computer.

\b \f \ \\ \ \r \a

Functions
In structural programming, the program is divided into small independent tasks. These tasks are small enough to be understood easily without having to understand the entire program at once. Each task is designed to perform specific functionality on its own. When these tasks are performed, their outcomes are combined together to solve the problem. Such a structural programming can be implemented using modular programming. In modular programming, the program is divided into separate small programs called modules. Each module is designed to perform specific function. Modules make out actual program shorter, hence easier to read and understand. A defined function or set of similar functions is coded in a separate module or sub module, which means that code can be loaded into memory more efficiently and that modules can be reused in other programs. After a module has been tested individually, it is then integrated with other modules into the overall program structure. Each module can be subdivided according to software engineering principles. The following structural chart shows the relation between each module and its sub module. Such a design approach is called top-down design.

Main Module

Module 1

Module 2

Module 3

19
Module 1A Module 1B Module 1C Module 2A Module 2B Module 3A

JNTUWORLD
Module 3B

C Operators Notes

The main module is known as a calling module because it has submodule. Each of the sub module is known as called modules. However, modules 1, 2 and 3 also have sub modules therefore they are also calling modules. The communication between modules in a structure chart is allowed only through a calling module. If module 1 need to send data to module 2, the data must be passed through the calling module, main module. No communication can take place directly between modules that do not have a clling-called relationship. This means that in a structural chart, a module can be called by one and only one higher module. There are several advantages of modular / structural programming, some of them are

Reusability: Many programs require that a particular group of instructions accessed


repeatedly, from several different places within the program. The repeated instructions can be placed within a single function, which can then be accessed wherever it is needed. This avoids rewriting of group of instructions on every access.

Easy Debugging: Since each function is smaller and has a logical clarity, it is easy to
locate and correct errors in it.

Build Library: The use of functions allows a programmer to build a customized


library of frequently used routines or system-dependent features. Each routine can programmed as a separate function and stored within a special library file. Building libraries reduce the time and space complexity and promote the portability.

Basics of Functions
A function by definition, is a procedure or routine. In other words, its a self-contained block of code that executes a certain task. Although some languages do distinguish between procedure and function, whereas a function returns a value of some kind and a procedure does not, C combines both functionalities into its definition. In order to use function in the program we need to establish 3 elements that are related to the function. Function Declaration: All identifiers in C need to be declared before they are used. This is true for functions as well as variables. For functions the declarations needs to be before the first call of the function.

20

JNTUWORLD

C Operators Notes Function Definition: It is actual code for the function to perform the specific task. Function Call: In order to use function in the program we use function call to access the function. The program or function that calls the function is referred to as calling program or calling function.

Ex: #include <stdio.h> print_msg(); /* The function Declaration */

void main() /* the main function */ { print_msg(); /* The function call */ } print_msg() /* the function definition */ { printf(this is a module called print_msg \n); }

21

JNTUWORLD

Anda mungkin juga menyukai