0% found this document useful (0 votes)
2 views22 pages

C 1 Unit

The document provides an overview of the C programming language, discussing its history, features, and the structure of C programs. It highlights the importance of C, the basic syntax, and examples of simple programs, including the use of functions and variables. Additionally, it outlines the steps for creating, compiling, and executing a C program, along with a brief mention of operating systems like UNIX and MS-DOS.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
2 views22 pages

C 1 Unit

The document provides an overview of the C programming language, discussing its history, features, and the structure of C programs. It highlights the importance of C, the basic syntax, and examples of simple programs, including the use of functions and variables. Additionally, it outlines the steps for creating, compiling, and executing a C program, along with a brief mention of operating systems like UNIX and MS-DOS.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 22
Overview of C_3 mputer languages are dj “orporating new features and G, the standardization committee of C fel , ; ir power and All popular co; lynamic in nature. They continue to topes aes ed out of Je by inex Cis no exception. Although C++ and Java ae would enhance a ' that a few features of C+-+/Java, if added to C ‘usually referred the usefulness of the language. The result was the 1999 AEE C. This version is s 689. The history and development of C is iustrated in ig. 1.1. ort all of . ‘although C99 is an improved version, still many commonly available compilers do not supp 5 C99 in an Shoview felures Inecrporated tn O89, We, therefare, discuss ull the New features added by appendix separately so that the readers wi ho are interested can quickly refer to the new material and use them wherever possible, IMPORTANCE oF c The increasing popularity of Cj ities. TREY © whose rich set of built Produce an overview Cader language ‘9 Specific features of C, we shall look a understand how they wok Tay Exemplify the elementary Coda Tees printing begins... +/ eeu Printf("I see, 1 renenber) printing ends... } if Fig. 1.2 A program to print one line of text - | S 4 Programming in ANSIC This program when executed will Produce the following output: I see, I remember i : et us have a close look at the program. The fist line informs the system that to fisad oo O ata tein and the execution begins at this line. The main( ) is @ special function ae by th C system to ell the computer where the program stees Every program musi have exactly one maj function. {f we use more than one main function, the compiler cannot understand which one marks th beginning of the program, ; i The empty pair of parentheses immediately following main indicates that the function main has p, arguments (or parameters). The concept of arguments will be discussed in detail later when we discus, functions (in Chapter 9), - . The opening brace “(" in the second line marks the beginning of the function main and the closin, brace "}" in the last line indicates the end of the function. In this case, the closing brace also marks the end of the program. All the statements between these two braces form the function body. The function body contains a set of instructions to Perform the given task. see iti In this case, the function body contains three statements’ out of which only the printf line is an executable statement. The lines beginning with /* and ending with */ are known as comment lines, These are used in a program to enhance its readability and understanding. Comment lines are not and */is ignored by the compiler. In general, occur—at the beginning, middle or end of a @ comment can be i line—"but never in t Although comments can appear anywhere, the comments inside comments. Once the Y cannot be nested in C. That means, we cannot have finds a closing token. The comment line compiler finds an opening token, it ignores everything until it mark. nd with a Semicoion (:) ‘Suppose we want to print the above quotation In two lines as I see, I remenber! This can be achieved by adding another printf function as shown below: printf("I see, \n"); printf("I remember !*); The information contained between the parentheses is calle argument of the first printf function is “I see, \n" and the second is simply strings of characters to be printed out. d the argume ii nt OF th | remer " 'e fu — ‘i en. This ents are Overview of C_5 Notice that the argument of the first printf contains a combination of two characters \ and 2 a ih, i of the string, This combination is collectively called the newline character. A newline chal omrucls the computer to go to the next (new) line. It is similar in concept to the carriage return key o1 in pewter After printing the character comma (,) the presence of the newline character \n causes the exing “I Temember "to be printed on the next ling. Ne cece 6 ahoved Se neoe acter i Ifwe omit the newline character from the first Printf statement, then the output will again be a single line as shown below. T see, I remember | This is similar to the output of the program in Fig, 1.2. However, and |. It is also possible to produce two or more newline character at appropriate places. For note that there is no space between, lines of output by one printf statement with the use of example, the statement Printf("I see,\n I remember 1"); will output I see, I remember 1 while the statement printf( "I\n.. see,\n. — . I\n. _ _ remember will print out = = Temember ! G3 Note Some authors recommend the inclusion of the statement, #include atthe beginning of all programs that use a for the functions printf and scanf which for more on input and output functions. ny input/output library functions. However, this is not necessary have been defined as a part of the C langi juage. See Chapter 4 » uppercase letters are used for symbolic. names representing constants. We may REMEMBER’. The above example that printed | see, ' remember is one of the sim highlights the general format of such simple lest programs. Figure 1.3 Programs. All C programs nee ‘da main function. Function name Start of program Program statements End of program Fig. 1 3. Format of simple C programs 6 _Progromming in ANSIC ROP ma ites) ; SD The main is a part of every C nt, Follow i are allowed, ing ion © main() int main() void main() main(void) void main(void) * int main(void . - ‘The empty me el nerdinces indicates that the function has no as This Y be : indicated by using the keyword void inside the parentheses. We an y 7 Ist Specify the key XxDlici Void before the word main. The keyword void means that the function ce Not return an tothe Operating system and int means that the function returns. ie Cai lue to the When int is specified, the last statement in the program must be “return 0°. For the we use the first form in our programs. SAMPLE PROGRAM 2: ADDING TWO NUMBE Consider another program, which performs addition on two numbers and displays the ru * The YY ink OP erating Alon 9 Syst, Sake of Sinpig complete program is shown in Fig. 1.4. P 7* Progranm ADDITION Tinea sy /* Written by EBG Vine-z sy nain() - I Tine ay { MM Vinegny 4 ‘int number; a Tine-§ */ : float amount; ie Tine-g */ / i Vine-7 #7 0d number = 100; I Tine-g +/ f I line-9 */ amount = 30.75 + 75.35; li Tine-10 +/ printf ("%d\n" number) ; * Vine-1 4/. f Printf("%5.2f", amount) ; I Vine-12 4/2) preiys ae 2) aot * Vinel3 */ | Fig. 1.4 Program to add two numbers This program when executed will produce the following output: 100 Overview of C_7 ‘The words number and amount eric data i The meric data. jable names that are used to store nui are variat um may be either in integer form or in the compiler what the va 'd to tell form. In C, all variables should eee aa ee al form. In C, ible names are and ‘at type of data they hold. The v: riable nai : i he declarations fore they are used. In lines § and 6, tI declared before they oe @ssigned to the integer variabl in line-10, the result of oe of two real numbers 30.75 and 75.35 is assigned to the floating point variable amount. The statemer hunber = 199; amount = 39, flue 10 it. This is done in tines 8 and 10. In line-8, an 'e number and ji 75 + 75.355 ‘ate Ralled the assignment statements Every assignment statement The next statement is an Output star Must have a semicolon at the end. tement that prints the value of number. The Print statement Printf("“id\n", number) ; Contains two arguments. The First argument *%a" tel Piler that the val number should be printed as @ decims Is the com lue of the second argument 21 integer. Note that these srouments are separated by acomma. The newline character \n Pauses the next output to PPear on a new line, The last statement of the Program Printf ("5.250 amount) ; ‘ount in floating point format. The format n floating poi and Pecification int, with five Places in al %S.2f tells the compiler f the decimal Nd of each y, °ar, and the cor; i "ure 8 Period of 19 SCS the following formula: ar of invest ts assumin 1 Tesponding amount, in Columns, The S2FS with an initial i stent of 5099 00. Program ae ae the ee ey t start of Year (1+ terest Tate) Value i Presents the y, f money at th Start of the year. 7 sae pheerdot *¥28r While coe amount = Value . make: ‘ She Value at the £nd Of the current Year as the value at start of the Next y, ear, le INVESTHEN T Pj Mdefine PeRtan mee ei define PRINCIPAL 00.00 Et MAIN mit PROGRAM Begy {fs rr 32_Progromming in ANSIC MS / BASIC STRUCTURE OF C RROG hare hean cn be vow fj The examples discussed so far illustrate tions. A function is a sul routing a BUT @S a group of building blocks called fe designed to ara ae ite we open ae = contain one or more sections as shown in Fig. 1.9. Documentation Section Global Dectar ‘Slobal Desaraton Sean ‘ain () Function Section Declaration part Executable part aR ip ys ~ Tae ‘Subprogram section Function 4 Function 2, (User-defined functions) Function n| Fig. 1-9 An overview of a C program The documentation section Consists of a set of the author and other details, which the programmer instructions to the compiler to link f symbolic constants, There are some variables that a Variables and are declared in the Comment lines giving the name of the Program, Would like to use later. The link section Provides ‘unctions from the system library. The definition section defines all re used in more tl than one function. Su global dectaratio ich variables are called global Section that is outside of all the functions. This ‘Section also declares all the user-defined functions, Every C program must have on Contains two parts, declaration Part and executable the executable we There is at least oni appear between ate ‘pening and the closing braces, 208 and ene ny us closing brace. The closing brace of thy le leclaration and exe ram. All Program section contains tho main une, A ' although they wo” appear in any order. Y may Alll sections, except the main function section may be absent when they arg rel Be Overview of C_13 pROG RAMMING STYLE unlike some other programming lan, eer is? free-form_language, That is, th ‘guages (COBOL, FORTRAN, etc.) C EGET Ota line we begin typing, While thig mec complet does not care, where on [Eee RK Ny should try to use this fact men’ Pe a licence for bad programming, feet programs. AILhOUSH several alterna svamage in daveloping readable eabeied Eelect one style and use it with Aobigcan Sites are possible, we should tof all, we must develop the hap ny are written in lowercase letters, Upponeect vue Programs in lowercase letters. C program statements Braces, 9roup program statements = a are used only for symbolic constants. proper indentation of braces and statement on the braces are aligned and the stater Since C is a free-form language, ments are indented in the program of Fig. 1.5. we can group statements together on one line. The statements a=b; xty4]; ze : can be written on one line as a a=bj xt yt; 26 aie! ‘The program bj x= y#4; z= atx; main( ) { printf("heT1o c"); . } may be written in one line like ; main( ) {printf("Hel1o ¢*)}s However, this style make the program more difficult to understand and should not be used. In this. book, each statement is written ona separate line. The generous use of comments inside a program cannot be overemphasized. Judiciously inserted comments not only increase the readability but also help to understand the program logic. This is very important for debugging and testing the program. EXECUTING A ‘C’ PROGRAM Executing a program written in C involves a series of ————— steps. These are: Scan the QR Code for accessing the online 4. Creating the program; deponctation of poi develop a gente 2. Compiling the program; program in C. The stration [aye Pay nl will cover the different stages of 3. Linking the program with functions that are needed program development including from the C library; and developing the source code 4. Executing the program. OR visit the link Figure 1.10illustrates the process of creating, compiling _http: ://qrcode flipick.com/index.php/359_ and executing a C program. Although these steps remain the same irrespective of the operating system, system commands for implementing the steps and conventions for naming files may differ on different systems. ‘An operating system is a program that controls the entire operation of a computer system. All input! output operations are channeled through the operating system. The operating system, which is an interface between the hardware and the user, handles the execution of user programs. Pr STS) ete Ze] 14 Programming in ANSI C ‘System Ready Source Program Edit Source Program Program Code Compile ‘Source Program C Compiler KI Object Code Link with ‘System Library, ] System Library I Executable Object Code Execute Input Data Object Code Data Error Fig. 1.10 Process of compiling and runnig a C program The two most popular operating systems today are UNIX (for minicomputers) and MS-Dos (for microcomputers). We shall discuss briefly the procedure to be followed in executing C programs under both these operating systems in the following sections, UNIX SYSTEM | Creating the Program _ Once we load the UNIX operating system into the memory, the computeris ready to receive program. The program must be entered into a file. The file name can Overview of C15 consist of letters, digits and special characters, followed by a dot and a letter ¢. Examples of valid file names are: hello.c program.c | ebgl.c ‘The file is created with the help of a fext editor, either ed or vi. The command for calling the editor and creating the file is | ed filename : Ifthe file existed before, itis loaded. Ifit does not yet exist, the file has to be created so that itis ready to receive the new program. Any corrections in the program are done under the editor. (The name of your system's editor may be different. Check your system manual.) ‘When the editing is over, the file is saved on disk. It can then be referenced any later by its file name. The program that is entered into the file is known as the source program, since it represents the original form of the program. Let us assume that the source program has been created in a file named ebgt.c. Now the program is ready for compilation. The compilation command to achieve this task under UNIX is ce ebgl.c The source program instructions are now translated into a form that is suitable for execution by the computer. The translation is done after examining each instruction for its correctness. If everything is alright, the compilation proceeds silently and the translated program is stored on another file with the name ebg1.0. This program is known as object code. Linking is the process of putting together other program files and functions that are required by the program. For example, if the program is using exp() function, then the object code of this function should be brought from the math library of the system and linked to the main program. Under UNIX, the linking is automatically done (if no errors are detected) when the ec command is used, If any mistakes in the syntax and semantics of the language are discovered, they are listed out and the compilation process ends right there. The errors should be corrected in the source program with the help of the editor and the compilation is done again. d and linked program is called the executable object code and is stored automatically in another file named a.out. Note that some systems use different compilation command for linking mathematical functions. ce filename - Im is the command under UNIPLUS SYSTEM V operating system. Executing sar Execution is a simple task. The command aout would load the executable object code into the computer memory and execute the instructions. During execution, the program may request for some data to be entered through the keyboard. Sometimes the program does not produce the desired results. Perhaps, something is wrong with the program logic or data, Then it would be necessary to correct the source program or the data. In case the source program is modified, the entire process of compiling, linking and executing the program should be repeated. faery elm elu Executable File zi ime name a.out. When we compi linker always assigns the sai T 7 . Note ie a ion by the executable object code of the new program, if whe = file wil i e) we should rename the file immediately by using the command, to bretm eed mv a.out name en . . Vet tion in the cc command as foll Iso achieve this by specifying an op! : a ce -0 name source-file This will store the executable object code in the file name and prevent the old destroyed. Ws: Ale rou Aha eee ge Maat 18S toy command. to the ce filename-1.c ... filename-n.c These files will be separately compiled into object files called filename-i.o and then linked to produce an executable program file a.out as shown in Fig. 4.14, Eo io ae | | Compiler and Preprocessor Fig. 1.11 Compilation of multiple files {tis also possible to compile each file separately and link them later, For exam cc -c modi.c cc -c mod2.c 2 mod2.c into objects files mod1.0 and mod2.0. They can by iple, the commands will compile the source files mod7.c and linked together by the command ¢c mod1.o mod2.o0 we may also combine the source files and object files as follows: ce mod1.c mod2.0 Only mod1.c is compiled and then linked with the object file mod2.0. This approach is useful when ‘one of the multiple source files need to be changed and recompiled or an already existing object files is ‘0 be used along with the program to be compiled, MS-DOS SYSTEM The program can be created using any word Processing software in non-document mode. The file name should end with the characters “.¢" like Program.c, pay.c, etc. Then the command MSC pay.c Describe macro substitution piscuss file inclusion directive Determine how compiler control directives are used Identify the preprocessor directives introduced ‘a part of ANSI additions. He INTRODUCTION Cis a unique language in many respects. We have already seen features such as structures and pointers. Yet another unique feature of the C language js the preprocessor. The C preprocessor provides several tools that are unavailable in other high-level languages. The programmer can use these tools to make his program easy to read, €asY to modify, portable, and more efficient. og js the source code before it passes The preprocessor, as its name implies, is a program that processes ; trough the compiler. It operates under the control of what is known as preprocessor command lines directives. Preprocessor directives ar placed in the source program before the main line. Before a process eee tig examined by the preprocessor for.any preprocessor ler, it is exal . ree fee passes tou pit 28 per the creatives) are taken and then the source a ere are any, Program i sompiler. a is handed over to the o eecal gyntax rules that are different from ihe normal C syntax. They ab processor directives follow spre io not require @ ‘semicolon at the end, We have already ce pain the symbol #in call Mie to a limited ‘Went, A set of commonly used Preprocesso e directives #define an é 44.1. dretves and their functions is Ve" " Taye gramming in ANSI C as _ Pro: Table 14.1 Preprocessor Directives rary Se Defines a macro substitution Undefines a macro Specifies the files to be included Test for a macro definition Specifies the end of #if. Tests whether a macro is not defined, Test a compile-time condition Specifies alternatives when #if test fails, is follows: These directives can be divided into three categories which are ai 4. Macro substitution directives. 2. File inclusion directives. 3. Compiler control directives. MACRO SUBSTITUTION stitution is a process where an identifier in a program is replaceg predefined string composed of one or more tokens. The preprocessor come, ’ Paar re task under the direction of #define statement. This statement, usually oo Fe macro definition (or simply a macro) takes the following general form: Hdefine identifier string m at the beginning, then the preprocessor replaces ever occurrence of the identifier in the source code by the string. The keyword #define is written bse shown (starting from the first column) followed by the identifier and a string, with at least one blank space between them. Note that the definition is not terminated by a semicolon. The string may bea text, while the identifier must be a valid C name. : There are different forms of macro substitution. The most common forms are as follows: Macro sub: oe C Describe macro. If this statement is included in the prograt 4. Simple macro substitution. 2. Argumented macro substitution. 3. Nested macro substitution. Simple Macro Substitution Simple string replacement i pales ce pl is commonly used to define constants. Examples of definition of constan's #define COUNT 100 #define FALSE 0 geting SUBJECTS 6 ee PI 3.1415926 fine CAPITAL “DELHI" Notice that we have written all macros (identifiers) in n to write all mac N hat we lacros (identi i it i i i eee tenn a ‘ d ifi Petes Itis a convention to write all maces capitals to identify them as symbolic constants. A definition, such as #define M5 The Preprocessor _449 piace all OCCUrTeNCeS Of M with 5, startin ig from the line of definition to the end of the program. er, a macro inside a string does not get replaced. Consider the following two lines: total = M * value; Printf("M = d\n", #); These two lines would be changed during Preprocessing as follows: total = 5 * value; printf("M = d\n", 5); is left unchanged. Amacro definition can include more wile power Notice that the string “M=%a\nan than a simple constant value. It can include expressions as well. rolowing are valid definitions: #define AREA 5* 12.46 #define SIZE sizeof(int) * 4 #define TWO-PI 2.0* 3.1415926 Whenever We use expressions f for replacement, care should be tal order of evaluation. Consider the ev; aluation of the equation ratio = D/A; where D and A are macros defined as follows: ken to prevent an unexpected #define D 45-22 #define A 78 +32 ‘The result of the preprocessor's substitution for D and Ais: “ratio = 45-22/78+32; ‘his is certainly different from the expected expression (45 ~ 22(78+32) Parentheses around the strings as: define D (45 ~ 22) Hdefine A (78 + 32) Itis a wise practice to use parentheses for expressi As mentioned earlier, the preprocessor performs a literal text substitution, whenever the defined ame occurs. This explains why we cannot use a semi Suggests that we can use a macro to define almost a Correct results can be obtained by using ions used in macro definitions. i#define TEST if («> y) #define AND #define PRINT Printf("Very Good. \n"); to build a statement as follows: : TEST AND PRINT The preprocessor would translate this line to if Gey) printf("Very Good.\n"); confusing or are error-prone, For exam in place of the token Some tokens of C syntax are mistake is to use the token = | token 8& Following are a few definitions that might be useful in building error free and more readable Programs: ple, @ common programming n logical-expressions, Similar is the case with the #define EQUALS 450 Programming in ANSI C AND && #define ot i eae NOT_EQUAL i= ena START main() { . } #define END - #define MoD e #define BLANK_LINE printf(‘\n"); #define INCREMENT + An example of the use of syntactic replacement is: START if (total EQUALS 240 AND average EQUALS 60) INCREMENT count; END Macros with Arguments The preprocessor permits us to define more complex and more useful form of replacements, |t takes the form: identifier(f1, f2,.- +--+ fn) Sing #define macro identifier and the left parentheses. The identifiers Notice that there is no space between the that are analogous to the formal arguments in a function fn are the formal macro arguments definition. There is a basic difference between the simp! of macros with arguments. Subsequent occurren Je replacement discussed above and the replacement ce of a macro with arguments is known as a macro ca ‘a macro is called, the preprocessor substitutes the string, replacing the (similar to a function call). When | parameters. Hence, the string behaves like a template. formal parameters with the actual Asimple example of a macro with arguments is #define CUBE(x) (x*x"x), If the following statement appears later in the program volume = CUBE(side); Then the preprocessor would expand this statement to: volume = (side * side * side )5 Consider the following statement: volume = CUBE(a+b) ; This would expand to: volume = (atb * ath * a+b); which would obviously not produce the correct results. This is because the preprocessor performs 2 blind test substitution of the argument a+b in place of x. This shortcoming can be corrected by usd parentheses for each occurrence of a formal argument in the string. The Preprocessor 451 exemple #define CUBE(x) this would result in correct expansion of CUBE(atb) as: volume = ( (ath) * (ath) * (a+b)); Remember to use paréntheses for each occurrenc ¢ of a formal argument, i ~ gome commonly used definitions are: ‘gument, as well as the whole string. (&)* &)"O)) Hef aa eae (((@) > (©) ? (a): (b)) #tdefine ((@) < (b)) ? (a): (6) #define ae 4,82) (0) > 0)? (%): 00) S15 #define STRGT(s1,s2) (stremp((s1,) (s2) J (stremp((s1,) (s2)) > 0) The argument supplied to a macro can be any series of characters. For example, the definition #define PRINT(variable, format) _printf(‘variable = %format \n’, variable) can be called-in by PRINT(price x quantity, f); The preprocessor will expand this as printf( "price x quantity = %f\n", price x quantity); Note that the actual parameters are substituted for formal parameters in a macro call, although they are within a string. This definition can be used for printing integers and character strings as well. Nesting of Macros We can also use one macro in the definition of another macro. That is, macro definitions may be nested. For instance, consider the following macro definitions. #define M 5 #define N MH #define SQUARE(x) (@)* 0) #define CUBE(x) (SQUARE (x) * (x) #define SIXTH) (CUBE(x) * CUBE(x)) The preprocessor expands each #define macro, until no more macros appear in the text. For example, the last definition is first expanded into ((SQUARE(X) * («)) * (SQUARE(X) * ()) Since SQUARE (x) is stil a macro, itis further expanded into (00700) * &)* (GD * &))* &))) which is finally evaluated as *°. Macros can also be used as parameters of other macros. For example, given the definitions of M and N, we can define the following macro to give the maximum of these two: fidefine MAX(M,N) (( (M) > (N) )? (M) = (N)) Macro calls can be nested in much the same fashion as function calls. Example: HALF(x) ee #define HALF(HALF(x)) fine Y - ed fe the following nested call to give the maximum Similarly, given the definition of MAX(2,b) we can ust of the three values x,y, and 2: MAX (x, MAX(y.2)) @S2_ Programming in ANSI C Undefining a Macro ; 7 Adefined macro can be undefined, using the statement #undef identifier This is useful when we want to restrict the definition only to a particular part of the program FILE INCLUSION Rees ‘An external file containing functions oF macro definitions can be inc} a part of a program so that we need not rewrite those functions 2 eat ons. This is achieved by the preprocessor directive #include “filename” ng the required definitions or functions. At this lied, OF may Discuss file inclusion | where filename is the name preprocessor inserts the ent filename is included within thi directory and then in the standard directories. ‘Alternatively this directive can take the form #include without double quotation marks. In this case, the file is searched only in the standard directories, Nesting of included files is allowed. That is, an included file can include other files. However, a fj cannot include itself. a fl If an included file i Let use assume that we have created the following three files: of the file containit ; a tire contents of filename into the source code of the program. Wher . When th ie cote quotation marks, the search for the file Is made fst in the cy Ten 5 not found, an error is reported and compilation is terminated. SYNTAX.C contains syntax definitions. STAT.C contains statistical functions. TEST.C contains test functions. We can make use of a definition or function contained in any of these files by including them in te program as: ; #include include "SYNTAX.C" #include "STAT.C™ #include "TEST.C" define = M 100 main () } COMPILER CONTROL DIRECTIVES ETE Peaster Pn ach Clean Sec) While developing large progr: : al pee programs, you may face one or more of the folov#l 1. You have included a file containing some macro definitions. It isa known whether a particular macro (say, TEST) has been defined i) header at However, you want to be certain that Test is defined (2"* The Preprocessor _453 gupe0se 8 customer has two different types of computers and you are required to write a program 2, Sufiwill run on both the systems, You want to use the same program, although certain lines of that must be different for each system, you are developing a program (say, for sales analysis) for selling in the open market. Some 5. {ystomers may insist on having certain additional features. However, you would like to have a single program that would satisfy both types of customers. suppose you are in the process of testing your program, which is rather a large one. You would 4 Tye to have print calls inserted in certain places to display intermediate results and messages in order to trace the flow of execution and errors, if any. Such statements are called ‘debugging’ statements. You want these statements to be a part of the program and to become ‘active’ only wien you decide so, solution to these problems is to develop different programs to suit the needs of different situations. _qher method is to develop a single, comprehensive program that includes all optional codes and then was the compiler to Skip over certain parts of source code when they are not required. Fortunately, { preprocessor offers a feature known as conditional compilation, which can be used to ‘switch’ on ma particular line or group of lines in a program. jtuation 1 tis situation refers to the conditional definition of a macro. We want to ensure that the macro TEST “aways defined, irrespective of whether, it has been defined in the header file or not. This can be chieved as follows: #include “DEFINE.H" #ifndef TEST #define TEST 1 #endif EFINE.H is the header file that is supposed to contain the definition of TEST macro. The directive. #ifndef TEST earches for the definition of TEST in the header file and if not defined, then all the lines between the ifndef and the corresponding #endif directive are left ‘active’ in the program. That is, the preprocessor irective # define TEST is processed. Incase, the TEST has been defined in the header file, the #ifndef condition becomes false, therefore ne directive #define TEST is ignored. Remember, you cannot simply write # define TEST 1 ecause if TEST is already defined, an error will occur. Similar is the case when we want the macro TEST never to be defined. Looking at the following ode: Hifdet TEST #undef TEST #endif ‘asa Programming in ANSIC | PQ . its definition is removed. 1 ed in the header file, ere in, fi This ensures that even if TEST is defi cannot simply say gundet TEST tive is erroneous. because, if TEST is not defined, the directive © Situation 2 veto make the program portable. This can be achieved as follows: The main concem here is code for 1BM_PC code for HP machine } If we want the program to run on IBM PC, we i #define IBM_PC Note that the compiler control directives are inside the function. Ca include the directive in the program; otherwise we don't. must be taken to put the # character at column one. ‘The compiler complies the code for IBM PC if IBM-PG is defined, or the code for the HP machine itis not. Situation 3 This is similar to the above situation and therefore the control directives take the following form: ifdef ABC group-A lines flelse group-B lines fendif Group-A li i up-A lines are included if the customer ABC is defined. Otherwise, group-B lines are include! i 4 The Preprocessor ass sue ging and testing are done to det ug} i ‘ect errors j oeeemic errors, it cannot detect 4 ful inthe program. While the Comp fing esults: ly algorithm where the ‘ompiler can detect syntactic y Program executes, but produces a ect wgng control directives as: #ifdet TEST { printf("Array elements\n"); for (i = 0; i di as defined by the compiler. However, program's source directory: directories. [LO 14.2] Program code in a systematic manner. [LO 14.1] that it is restricted to only a specific part in a proge rective searches the file only in the standard direc the #include "filename" directive searches the fie int and if the file is not located, it then search for the file in the sta Use #itndef to endif directives for conditional compilation of program code. [LO 14.3]

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy