You are on page 1of 129
Contents Introduction 1 Declarations and Initialization 2 Control instructions 3 Expressions 4 Flcating Point Issues 5 Punctions 6 TheC Preprocessor 7 Pointers 8 More About Pointers 9 Amays 10 Strings 11 Structure, Unions and Emumerations 12 InpuvOupet 13 Command Line Arguments 14 Bitwise Operators 1S Subsleties of »pedef 16 ‘The const Phenomenon 17 Memory Allocation 18 Variable Number of Arguments 19 Complicated Dectarations 20. Library Functions wi " n 37 47 35 @ 31 107 129 141 157 169 119 189 227 237 Introduction “There is no dearth of good C programming books in the marke. However, I found that there is not much material which could help a CC programmer to test his prograrnming strengths, help improve his ‘confidence and inthe process hone his C skills. Hence this book: ‘This is not text book on C. Infact its ar from it. Itcontains a lot of questions sogregated topic-wise according to my perception ofthe language. Almost all the questions are real one's tsked by real people sttempiing to learn or program in C “There is no reason why you should read the questions in the same order as they appear inthis book. Youcan pick up any topic that you think you are good at (or poor at) and tr to test your skills on that topic. “There is a good chance that i you ae learning oF using C-and you hhave questions about C that area’ answered in any of the other books {you've checked, you would find them answered here. twould be 109 much to expect that you would find in this book answer to every ‘question you would have when you're programming in C. Ths is [because many ofthe questions that may come up in your program: ‘ming would have todo with your problem domain, whereas this book Concentrates only an the C language. Also it doesn't cover every aspect ofevery operating system under which Cis running, Problems specific to an operating systems, and general-purpose algorithms are properly discussed in books devoted to those topics. ‘At the end of each chapter you would find correct answers t0 the ‘Questions in that chapter. You would find some answers more laborate than others. At first sight this may seem unnecessary. However, Ihave done this to give you the complete picture rather than oversimplifying or leaving out important detail. Ihave tie to avoid the questions whose answers ate most obyious because te dea was not fo inerease the numberof questions, bt to presen questions which would force the readers to think tice before asivering, Thats tune withthe pit of C- be precise, brevity has its own importance So rll your sleeves and get on with the real questions. Good vc! Yashavant P. Kanetkar Nov., 1996 Chapter 1 Declarations and Initializations Qu What would be the ouput ofthe following program? 1 charfor 1,02 print (Sed ua ast), abe (2)) ] Q 2 What would be the output ofthe following program? inux=<0. rain) ints 20: rit (rex): Q 2 What would be the output ofthe f lowing program? main() ( int=40; vx =20: pri Wa" x); ) ae Qu Is the following statement «declaration ora definition? center int Qs ‘What would be the output ofthe following program? rman) { ext it; 120; print Seize ()) 4 Would vary from compiler to compiler Error, undefined powp Isittrcthata global variable may have several declarations, but only ‘one definition? Qu Is tare that function may have several declarations, bu only one Aefinition? Qs Inthe following program where is the variable « getting defined and, where is it petting declared? rin) i exemirta; Pit (St); ima=20; Q 19 ‘What would be the output of the following program? man) 4 tom nt a; i ("ask ) fta=29 ‘Test Your C'S A 20 Bo ©. Garbage value D. Error Q 10 ‘What's the difference between a defintion and declaration of a variable? Qu Ifthe definition ofan external variable occurs inthe source fle before its use ins parieuar function, then there is no need for an extern ‘declaration inthe function. Q iz ‘Suppose a program is divided into three files fl, f2 and 3, and a variable is defined in te file fT but usedin the files 2 and. Tn such, Aacase would we need the external declaration for the variables inthe files 2 and /3? Q 12 When we mention the prototype of a function are we defining the function or declaring i? Qiu ‘What’ the difference between the following declarations? _)6| Chapter 1: Declarations and Initilisations cextem int un); infu); Q us Why does the following program report ree fanction display) man ( spay) on) ( ) Q 16 What would be the onpat ofthe following program? nt ("ncitnanger’) ‘main() i extort fn (fost); ita a=tun(at¢) print (90a) ) intin aa) oat aa { ) retum (it) aa); 6 Test Your C Skills Bas Error Point out the error, if any, in the following program. stucteme char namel20; int age: ) some mare code may go hee“ (Chapier I: Declarations and Iitialisations z Q 18 If you are to share the variables or functions across several source files how would you ensure tha ll definitions and declarations are ‘consistent? Q 10 How would you rectify the error in the following program? 1 stuctemp }; 7 any cher protlypes may o here"! struct emp ( char namet2; intage: rit wks i", 9:nae, 8.298); ) Q 120 Global variables are available to all functions. Does there exist a ‘mechanism by way of which Lean make it available to some and not toothes _ es Test Your CStits (Chapter 1: Declarations and Initialisations Q 121 ‘A. 0.0.000000 What do you mean by translation uit? es D. None ofthe above Q 12 ‘What would be Q 1x Some books suggest that the following definitions should be he output ofthe following program? rn Beet ye ned nate Ishomen? ria) -(2.8 uaa (284 1222 pd a a As Settonpe ato) ) ‘AL Garbage values Q 125 a 933 @ 322 nou heme fay jn allowing progam, 32 Peau or ian, inte loins og rest) Q 1 ( rac) ‘What would be the output of the following program? ge) tat) mmain() a der ce 5 Pet ate sharma ; item: Q 1 hae b Boi: eosin, nt ling promen bs sat i ani hen i, nt lowing ro pir cet ea al) ac i 1 lo Test Your C Skills Chapter 1: Declarations and Initialisaions uy union a ais in char ch}; 20 40. Incase ofaconilict between local variables, the one which is 1 more local that gets the priority union a2 = 512; pain kd, zn) iin ) Q 17 ‘What do you mean by scope of a variable? What are the 4 ifferent Iypes of scopes that a variable can have? Q 12 What are the different types of linkages? Answers Au 42 A iw 20, Whenever there isa conflict between a local variable anda global, ‘variable itis the local variable which gets a priority Declaration A 15 D. extern int ‘isa declaration and nota definition, hence the eror. A 16 Yes Aw Yes A 18 extern int ais the declaration whereas int a A 19 A 2 ‘Test Your C Skills A 110 In the defintion ofa variable space is reserved for the variable and Some intial values given toi, whereas a declaration only identifies the type ofthe variable for function. Thus definition isthe place where the variable is created or assigned storage whereas declaration refers toplaces where te nature ofthe variables stated butno storage isallocated. Ai Yes A 1 We are declaring it. When the function alongwith the statements ‘belonging to it ae mentioned we are defining the function A iu Thereis no difference except forthe fact that the first one gives aint thatthe function fun() is probably in another source file. A 115 Here display(is called before itis defined. In sach cases the compiler assumes thatthe function display) is declared as (Chapter 1: Declarations and Iniialisations 13 int depay|) ‘Thats, an undeclared function is assumed to return an inrand accept ‘an unspecified number of arguments. Then when we define the Tunction the compiler findsthatitisretuming voidhencethecompiler reports the discrepancy. A 116 1D, The erroroceurs because we have mixed the ANSI prototype with K&R style of function definition ‘When we use ANSI protptype fora funetion and pass a flat tothe fanction it is promoted to a double, When the funeton accepts this double into afloat type mismatch occurs hence the eror ‘The remedy for this error could be to define the function as: intun oataa) { } Aun Because of the missing semicolon atthe end ofthe structure deol tation (the intervening comment further obscures it) the compiler believes that unt) would return something ofthe the type struct emp, Whereas in actuality itis attempting to return an in. This causes & Imismatch, hence an error results 1 Test Your C Skills A 18 ‘The bes arrangement sto place each definition in a relevant «file ‘Then, put an external declaration in a header file (file) and use include to bring inthe declaration wherever needed, The « file which contains the definition should also include the ‘header le, so that the compiler ean check thatthe definition matches the declaration, A 119 Declare the structure before the prototype off) A 120 'No, The only way this canbe achieved! to define the variable locally ‘in main) instead of defining it globally and then passing it to the functions which need it A 121 ‘A translation unit isa set of source files seen by the compiler and translated aa unit: generally one file, plus all header files men- tioned in include directives. A 122 , When an automatic array is partially initialised, the remaining aray elements ae initialised to 0. Chapter 1: Declarations and Intilisations 15 A 123 ‘A. When an automatic structure is partially intalised, theremaining elements of the structure are initalsed 00 A 194 Pre-ANSI C compilers had such a requirement. Compilers whic conform to ANSTC standard do not have such 2 requirement A 135 Here we are iniialising the function pointer p to the address of the function fun) But during tis initialisation the function has not been defined. Hence an eror. ‘Tocliminat this error add the prototype of the ju) before declara- tion ofp, as shown below: ‘ter int fun); orsimply inh); A 126 Ina pre-ANSI compiler union variable cannot be initialised. How: lever, ANSI C permits niilisation of first memeber ofthe union. _Test Your C Skills ‘Scope indicates the region over which the variable's declaration has tan effet. The four Kinds of scopes are: file, function, block and rottype, A 1298 There are three diferent types of linkages: external, internal and ‘none. Extemal linkage means global, non-static variables and fune- tions, infernal linkage means static variables and functions with fle Scope, and no linkage means local variabl Chapter 2 Control Instructions Q 21 What would be the ouput ofthe following program? main() C inti=a; switch (1) faut: print (oA mouse an elephant uly te case print (oBreeing rabbits sa hare raising xperoce’) beak pant ( break oxo print (“i pracice makes pact. then nobody's pare) lenis day’) Q 2 Point ou the error, if any in the for loop jae Test Your C Skills i inti=t forts) c prt (6a eo) W(i> 10) brook A. ‘Tecondionnthejor lop sams. ar renee aa €._Thofrloop aldo epaed we op pee Q 2s Point out the error, if any, inthe while loop. ( iti=1 while} rine) itli> 1) ca: ‘The condition inthe while loop is « must There should beat least a semicolon in the while). The while Toop should be replaced by afer loop. Noerror. poe ‘ontrol Instructions 1 Chapter 2: Q 2 Pint out the errr, if any, inthe while loop. rman() ( inti=1; while (<= 5 print 401) lia) (ete here Point out the error, if any in the following progracm main’) 1 inti=4,j=2, swich (7) ( case et "niTo ors human, to ergiveis aginst company pe break; case iit (you have nating ted, dont doithere") bre: Test Your Q 2% Point out he error, if any, in the following program. main) in sath (i ( case 1 print nRadoactve cals have 18 haves) case 1°2+4 Bote for ent ing wai”) Point out the error, ifany, inte following program. rmain() imta= 10: sich (a Print (Programmars never ce. They just gets nthe processing’): Skills Chapter 2: Control Instructions Q 28 Point out the error, if ny, in the following program. main) ( inti= switch (i) print |"Holo'); common forboth cases “pint "nits uit") break case? print (oMenay isthe root ofall eat) break } 1 Q 2 Rewrite the following st of staemens using conditional operators. bbla=1,0; H(a>10) b=20 Q 210 Point out the error, ifany. inthe following program. sain) fl ima=10, Test Your C Skills b= 200: pir (aac) } Q aun What would be the ousput ofthe following program hart] = "Parte musisars ae semiconductors; print a> 10 S505": st). ‘A. Part-time musicians are semiconductors B. _Part-time musicians are semiconductors ©. Enor D. None of the above Q 22 Q an Q 2 We want to test whether a value lies the range 2to4 or 507. Can wwe do this using a switch? _ Chapter 2: Control Instructions 23 Q 2s The way break is used to take the contol out of switch can continue be used fo take the control tothe beginning ofthe switl? 107b=20: dummy Note tha the following would not have worked a> 107D=20:5; A 20 ‘Walue required in function main(). The second assignment should be ‘written in parentheses as follows: ae570=100:(D=200) Chapter 2: Control Instructions 2s A 21 A A 212 Asfarasefficiency isconcemed there would hardly be any difference fatal. Ifthe cases ina switch are sparsely distributed the compiler may internally use the equivalent of an etre chain instcad of compact jump table. However, one should use switch where one can Mis definitely a cleaner way o program and certainly isnot any less efficient than the ielse chain, A 218 No. The cases in a switch must either have integer constants of constant expressions A 2u Yes, though ina way which would not be very practical ifthe ranges Ae bigger. The way is shown below. e Sich (2) ( case? case case 7 some statements broek case case 6: case 7 * some cer statements Chapter 3 break; Expressi Tens: pressions Q 21 What would be the output ofthe follow rman) fl Satc int a0) ed eS, la): What would be the output ofthe following program? print (i) ) 28 Q 33 “The expression onthe right han sie of && andl operators does not get evaluated if the left hand side determines the outcome. eTrvelFalse> Q v4 ‘What would be the output of the following program? ( iti=2; pind (ed Se 4,448); a4 43 44 ‘Output may vary from compiler fo compiler. Q 35 ‘What would be the output ofthe following program? pope ‘main() 1 imtx=10,y=20,25,1 print (rk) Chapter 3: Expressions 9 © Enor D. None ofthe above, Q x6 ‘Are the following wo statements same? ac207b=30:0 (ae=20)?b:c Q a7 Can you suggest ay other way of writing the following expression Such that 30 is used only once? ‘ Sook Q 38 How come thatthe C standard says tha the expression 0 is undefined, whereas, the expression [ates Raine Is perfectly legal Q 39 If afi] = i++ is undeined, then bythe = 7 by the same reason /= i + J should also be undefined. But ici no so. Why? 30 Q 30 Would te exesion p++ Q an Inthe fotlowing code in wh be disallowed by the compiler, order the functions would be called? aft (25, 14)°12( 124) +100) fA BRA The order may vary from compiler to compiler None ofthe above pore Inthe following code in which onder the functions would bec 11 (23,14)"2(124)) +180; 1.2.0 Bat The onder may vary from compiler to compiler None ofthe above Q 218 ‘What would be the output ofthe following program poe ini=-3) —_ ions 31 (Chapter 3: Expre mati 8K 44] ok “atid ed Md km) Q 2 ‘What would be the output ofthe following program? rran() print (MoS a, ' Q ss Pas i ipa Rating pop an) Simi: -3,j=2,k=0,m; Desa of ab ok Print (ins 6d a, 8,m) , Q a6 What would be the ouput ofthe following program? main) { inti=-2,) m=ssi8a 2 os Test Your C Skills Chapter 3: Expressions 33 ait (rsd 5d ea km) A } A 36 Answers. mAs oor ‘That's what some of the compilers would give. But some other ‘compiler may give a different answer. The reason is, when single ‘expression causes the same abject to he modified orto be modified and then inspected the behaviour is undefined A 32 4. Bu basicaly the behaviou® is undefined forthe same reason asin 311 shove, A 33 “True, For example if ais non-zero thea b will not be evaluated inthe expression all b A 34 1. The order of evaluation of the arguments to @ function call is, unspecified A 35 No A 37 (a.ce20)7 8b: 8c) =30 A 38 According fo the C standard an object's stored value can be modified only once (by evaluation of expression) between two sequence points. A sequence point accu = a the end of full expression (expression which isnot a sub-expression ina larger expression) + atthe &&, lland 7: operators = atafuncton cal (afterthe evaluation of all arguments, jst before the actual eal) Since in the frst expression ‘is geiting modified wwiee between two Sequence points the expression isundefined. Also, the secondexptes- sion is legal because a sequence point is occurring at and iis, Betting modified once before and once after this sequence pont A 39 The standard says that if an object is to get modified within an expression then all accesses ot within the same expression must be for computing the value to be stored in the abject. The expression ali] = i++ is disallowed because one ofthe accesses of tthe one in ‘fi has nothing to do withthe value that ends up being stored in In this case the compiter may not know whether the access should fore oF aftcr the ineremented value is stored. Since od way to define ithe standard declares it as undefined. i+ [isallowedbecause ‘isaccessed take pla there's Asagainet this tho expr to determines final value A 310 No, Because here even though the value ofp is accessed twice itis used to modify two diffe Abaaatt (C. Here the multiplication will happen before the addition, but in which order the Functions would be called is undefined A 32 . Here the multiplication will happen before the addition, but in ‘order the functions would be called is undefined. In an arith metic expression the parentheses tll the compiler which operands {20 with which operators but do not force the compiler to evaluate A 313 Chapter 3: Expressions Chapter 4 Floating Point issues Qu ‘Wat would be the output of the following program? ( foata=0.7 il(a ae int, 19 (38.0)); ‘Would the following prin) print the same valves for any value of a main) fala; ‘oan (t8a); prin (‘Se/arata)> print (%t 3" a); Q 46 ‘We want to round off x, afloat, to an int value, The corect way to 050 would be A. y=(imty(x+05); int (x +05); (int) +05; CGint) (int) x05 ) Qa Which error are you Tikely 10 get when you run the following rogram? aa stuctem, i char namef20 fat sal; = “ Tes Your uly (hater 4 lang Pon wes 4 i iat shel yu doo ea he cota 3.14 fa? bec npato flied jie dhe) Qun ‘a a nao bt) ! What shoud yu do eae cmt 3.14 long double? A. Susp pointer cnreion Ls Bloating po oma one a ©. Chmote scan stacey Sng cnt esl ne tus Yat wuld e upto folowing program? 48 & What causes the errorin problem 4.7 above to aceur and how would you rectify the error in the above program? Q 49 ‘Which ate the three different types of real datatypes availabe in and what are the format specifiers ase for for therm? Q 410 By default any real number ested as float Adouble Tong double spends upon the memory model that you are using Q an poe> mi) it W350 c,sizao (3,14) szeo( 3.14), sizeof (2.141) ); } 444 4 Garbage value Garbage value 4310 Exor Q a4 The binary equivalent of 5375 is pae> A. to1,101110111 B. toro © 01011 B. None ofthe above Q 15 How floats are sored in binary foum? : il 2 — Test Your C Skills Chapter 4: Floaiing Point Issues a Q 46 Answers A float occupies 4 bytes. Ifthe hexadecimal equivalent of each of As these bytes is A,B, CandD, then whe this lat is storedin memory these byes get sored inthe order i A aBcD B DCBA A #2 oxABCD D. OxDCBA B Q an A 43 If the binary equivalent of 5.375 in normalised form i 0100 0000, D 1010 1100 0900 0000 0000 000, what would be the ouput ofthe following program? Py man) { fosta=5375; char’p; ini; =(cher*) a: for(i=0sie=3;H4) pr ("402 (unsigned cha) pf) 40Ac 0000 04CA 0000 (0000 Ac40, 0000CA 04 poe 'No, ince we have not included the header file “math.h” A 45 No. For example, for 1.7 the vo prin wool! print diferent A ts A A 47 “ Test Your C Skills A 48 What causes the lating point Formats not linked” error to occur? ‘When the compiler encounters a reference tothe address of alot, itseis flag to have the linker link in the leating point emulaior. A ‘oating point emulators used 1o manipulate oating poin: numbers, in runtime library functions like sce) and ao). There ate some ceases in which the reference to the float isa bit obscure and the ‘compiler does not detect the need forthe emulator. These situations usually occur during the intial stages of program development. Normally, once the program is fully developed, the ‘emlator wll be used in sucha fashion thatthe compilercanaceurate~ ly determine when to link inthe emulator ‘To force linking of the floating point emulator into an application, {just include the following function in your program vod LinkFoat (void) ( foata=0, b= Ba; cause emulator tobe inked) 2°; / suppress wating -var roused") ) ‘There is no need to call this Func A 49 from your program. oat byes Sf ouble Sbyes “lf long double 10bytes LE A 410 zz Chapter 4: Floating Point Issues 4s B A au Use314t A 4122 Use 3.141 A 413 e A 41 B A 415 Floating-point numbers are represented in IEEE format. The IEEE, forma for floating point storage uses a sign bit, a mantissa and an exponent for representing the power of 2. The sign bit denotes the Sign ofthe number: a 0 represents a postive value and a1 denotes a negative value. The mantssaisrepresentedinbinaryafterconverting itto its normalised form, The normalised form results ia a mantissa ‘hose most significant digit is always 1. The IEEE format takes !dvantage of this by not storing tis bit at al. The exponent isan Jeger sored in unsigned binary format after adding a positive Integer bias. This ensures that the stored exponent is always positive. The value ofthe bias is 127 for loars and 1023 for doubles, A A 416 Aan Chapter 5 Functions Q 61 What would be the output ofthe following program? rman() c inta,b; mig (1235 = au (123) print ("Sed a,b); ' i) aint = 0 ing it{nl-o) reun(s) # ‘est Your C Skills “Chapter 5: Functions Q «2 What error would the following function give on compilation? Qu ‘Point out the error in the following code {int itd) mah) ( ina 4223; uma ) ) ‘A. Missing parentheses in return statement rn) B. The function shouldbe defined as int a, ib J © Redecaration of @ p(w"); D. None ofthe above Qs. 65 There isa mistake inthe following code. Add statement in it to int out the error if any, in the following function. “ma ) man) { in; inta; b=1(29); ant 10,314); | ab}; int, ) (ta) {(inta, fatto) t 82207 retam{ 10): tum (20); ratum ( (ot) 2a + bb ) ) Q ie A function cannot be defined inside another fuction, 30 Test Your C Stills Q 57 Will the following functions work? H(itayinb) ( retum (2(20)); ‘linta) i 4 Q ss ‘What are the following vo notations of defining functions common: ly known as: ret (a*a): in (int a, oats) ( soma cade ) intt(a.b) inca: foatb; i 1 Q 59 ‘Ina function two rium statements should never occur. some code */ ‘Chapter 5: Functions 3 Q 510 “Ina function two return statements should never occur successively, “cTrvelFalse> Q sn “In C all functions except main() can be called recursively. TruelFalse> 512 Usually recursion works slower than loops. 53 ttc that oo many recursive calls may result into stack overflow”? es!No> but ‘many times the following program would print Jamboree"? ) “ain Infinite numberof times 32767 times (65535 times 5: Functions 3B 52. Test Your C Skills D. Till the stack doesn’t overflow A 56 Answers: A 51 mA 5.7 612 A 52 58 ic ‘The first one is known as ANSI notation and the second. known as ighan and Ritchie or simply, K & R notation. A 53 59 Adi the following function prototype i main fea (int oat); A 54 5.10 Inspite of dofining the Function () as returning void, the program is ‘eying to collect the value retuned by f) in the variable a A 55 bu Ise. Any function including main() can be called recursively. ‘return stalement cannot be used as shown with the conditional ‘operators. Instead the following statement may be uscd ee retum (a> 20710:20); 3 Test Your C Skills A 53 Yes A 518 Chapter 6 The C Preprocessor Qu ‘Ifthe file tobe included doesn’t exist, the preprocessor flashes an error message. Q «2 "The preprocessor can trap simple errors like missing declarations, nested comments or mismatch of braces. Q 63 ‘What would be the ouput of the following program? ‘eatne SOR x") “mai() C inta,b=3; a=80R(b+2); Print (wea) A 2 Bo 56 ‘Test Your C Skills © Bror D. Garbage value Q s4 How would you define the SQR macroin6.3 above such that itgives the result oF a as 25, Q os Wat oil te he oupu fhe following program? ‘eine CUBED) x") main() 1 inta,b=9; 2= CUBE (++): int “ned ea, ) Q v6 Indicate what would the SWAP macro be expanded toon preprocess: ing, Would the code compile? ‘deine SWAP(2, 0,0) (21 vt) aabbe1:) Intx=10,y=20; SWAP (x,y nt) Print (Sd x,y) ) Qa "In which line of the following program an error would be reported? “FLOATPTR a, Chapter 6: The C Preprocessor ‘How would you modify the SWAP macro in 6.6 above such that tis able to exchange two integers. Q vs What isthe imitation ofthe SWAP macro of 6.7 above? Q «9 4, deine CRCUMIA)(3.14° RR); 2 main) a ( 4 5 8 7 628) a Print ( Nnotbedygoak 8 H Q 610 ‘What isthe typeof the variable din the following declaration? ‘eine LOATPTR Rat * 38 ‘ess Your € Skills, Q on Tsitnecessary thatthe header files should have extension? Q oe ‘What do the header files usualy contain? Q a Would it result into an error if header file is included twice? : Q 614 ‘How can a header file ensure that it doesn’t get included more than Q os (nincasion, where arth header es searched for? Q 4 Would the following rypeder work? ‘ypodel nude |; print (sea); at would be the output of the following program? "pri MESS"); ld the following program print the message infinite number of ls? in INFINTELOOP while (1) oo ‘Test Your C Skills main) ( INFINTELOOP. Print (“Grey hare) 1 Q 620 ‘What would be the ouput of the following program? ‘éetne MAX(,b) (a>b7.a:b) mman|) ( ionx; x= MAX (942,247); ail Q 621 ‘What would be the output ofthe fllowing prograrn? fedeine PRINT in) print (dl * it) main) ‘What would be the output ofthe following program? er 6: The C Preprocessor 61 “tetine PRINT int) print (ot = td int) How would you modify the macro of 6.22 such that it ouputs: x=2 y=3.2=4 eit Tips Traps") 625 fine the macro DEBUG such tat the following program outputs; @ Test Your € Shits Chapter 6: The C Preprocessor 63 ot PAINT(a.b.¢); DEBUG (x,%d); ers DEBUG (2,9), DEBUG (eh, %e}: 61 , True Q 528 | 62 | ‘What would be the output ofthe following program? Aetna ste False Aelia Yate) ee ‘datne oper mutily A 63 mai) i har ‘qperame = Xs (ope); Bint ( "6s" opemame 'B. Because, on preprocessing the expression becomes d= (3 +2* 243) A 64 Adon SOR(o) (4 * 2) A 65 Q 2 Write the macro PRINT for the following program such that it outputs: 27 6. Though some compilers may give thi asthe answer, according fo the ANSI C standard the expression b++ * b++ * b++ is undefined. Refer Chapter 3 for more details on this A 66 (int: n4225 2o=3 by be13); a. ‘Test Your C Skills ‘This code won't compile since declaration of reannot occur within parentheses A 67 ‘ene SWAP(a,b,c) ct;t=a,a=b,b=t; A 68 cannot swap pointers. For example, the following code would not compile. amines A 69 Line number 7, whereas the culprit is really the semicolon in line ‘number 1. On expansion line 7 becomes if((3.14 * 1.0 * 1.0); 628 ) Hence the error. A 610 {float an nota pointer to afloat, since on expansion the declaration becomes: Neat ',b; Chapter 6: The C Preprocessor 65 A 61 No, However, traditionally they have been given a .h extension to dontify them as something different than the program files A 612 Preprocessor directives like Alene, structure, union and enum dee- Iazations, pedef declarations, global variable declarations and ex- {eral function declarations, You should not wrtethe actual code i. function bodies) or global variable definition (hat is defining oF fntialising instance) in header file. The include directive should be used pullin header files, not other files, A 613 ‘Yes, unless the header file has taken care to ensure that i already included it doesn’t get included again. A ou “All dectarations mastbe written inthe manner shown below. Assume ‘that the name ofthe header file is FUNCS H. hanes’! ‘indo|_FUNCS ‘iaine_FUNCS (ral declarations would go here" Henat Now if wo include this file twice as shown below, it would get included only once Chapter 6: The C Preprocessor or fa Test Your C Skills ‘include “goto.” A 620 ects po0e mreb|) c 9 sae code") , A 621 A 615 234 included using <> the files get scarched inthe predefined (can be A 62 hanged) include path. included withthe "syntax in aon 69 Bea ‘hepredefined include path thefles ako get searched inthe curent Bes siretory (usualy the directory fom which you invoked the com pile). A 622 | eine PRINT it) pnt int "= it) A 616 ‘main() ( Na Bi pis wine eg itso PRNT(y): A 617 PRINT (2); , No. Even though the defi in this case (NOTE being undefined) and the if block doesn't go for compilation ertors in it are not permitted, A 68 Mess A 619 Yes ‘The rule is if the parameter name is preceded by a # in the macro ‘expansion, the combination (of # and parameter) will be expanded, Jintoa quoted string with the parameter replaced by the actual argu ‘ment. This can be combined with string concatenation to print the ‘output desired in our program. On expansion the macro becomes pant (x= Sx) “The two strings get concatenated, so the effect is iret x= 98x) Test Your C Skills A 624 ‘Yes. The output would be TipsTraps. In fact this esulthas been used, in 6.23 above. A 625 ‘ine DEBUG vat) print (“DEBUG var A 626 et var) ‘multiply Here two operations are being caried out expansion and stringing, ‘Xsir) macro expands its argument, and then str) stingies A 627 ‘ne PRINT( vat, var, va) pint ("Wart "= "ard" = ed ‘vara"= "6d" vat var, va) Chapter 7 Pointers Qu "Can you combine he following {Wo statements into one? harp; ‘p= malo (100); Q 2 Can you spt te followin statement ino vo statement? harfor ‘or = (char far *) OxBB000000L; Q a3 Ae the expressions "pire and ++%ptr same? Q 4 ‘Can you write another expression which does the same job as 4p? 0. Test Your C Sills Q is ‘What would be the equivalent pointer expression for refering the same element as aff J0AI007 Q ve ‘What would be the ourpr of the following program? ~ intan{}=( 12, 19,14 15,16): it "nthe sia a), seo (ar), sia an]}): ) Qa ‘What would be the output of the following program assuming that ‘the array begins at location 1002? ‘main() intIs1=( 1.2.34, 5.8.7.8, 910,14,12 bh it int ou Su lO} 1, "(D+ 1),°(" (2-40) 41)) ) Chapter 7: Pointers 78 ‘What would be the output ofthe following program assuming that the array begins at location 1002? int a2]914 = Se ra Sao Bee 3, 0 Prin retusa Se", "a 79 the following program how would you print 50 using p? int al}= (10, 20,90, 40,50); char"p char"); Test Your C Skills Q 710 werent Qi Inthe following program adda statement in the function fi) such that address ofa gets stored inj. ran) i ing; voifun int , fecal von (int) { in: ‘add staoment hee *F it Q 12 How would you declare an array of thre function pointers where ‘ech function receives tvo int and returns afloan? Q 73 ‘Would the following program give a compilation error or warning? main) foul the fllowing program compile? i) ina=10,4); void"; jake 8a; ie ke pit (we ak): 715 fould te following code compile successfully? int) pet" 71"Sundaran"}); Answers Ai char p=malee (100); A 72 hari ser ‘sur= (char far*) 8000000; A 73 [No, *ptr+-+ increments the pointer and not the value pointed by it, ‘whereas ++4ptr increments the value being pointed toby pr. A 74 Cries A 7 "COC Esse) A 76 1022 Az 004 2 2 79 (asia *((int*) +4); 710 tot of places, some of which are: Accessing aay or string elements Dynamic memory allocation all by reference Implementing linked lists, trees, graphs and many other data structures rt 712 (or) in it) 71s > Here no typecasting is required while assigning the value to and om k because conversions are applied automatically when other ite types are assigned to and from void *. 16. ‘Test Your C Stills, A 714 No. Aneror would be reported in the statement ++ since arithmetic ‘on void pointers is not permitted unless the void pointer is ap- propriatly typecasted A 716 Yes. It would print m of Sundaram. Chapter 8 More About Pointers a1 $the NULL pointer same as an uninitialised pointer? 82 nwhich header file is the NULL macro defined, as is it that fr lage memory models NULL has been defined as ‘and for small memory modes a just 0? 84 a's the difference between a nll pointer, a NULL macro, the "IINUL charsctor anda null string? 8 ‘est Your C Skills Q 86 ‘What would be the outpat ofthe following program? Inthe programming yl adopedin 8.6 good? Q 88 ‘What would be the output ofthe following program? ‘nce ‘sto main) ( Print ("Se sizeot (NULL), sizea |"); Q a9 How many bytes are occupied by near, far and huge pointers? Chapter 8: More About Pointers 2 Q a0 Whatdoes the error"Null Pointer Assignment’ mean and whatcauses | thiserror? Q sn ‘How do we debug a Null Pinter Assignment error? Q sz ‘Can anything else generate a Null Pointer Assignment eror? Q sn ‘Are the thre declarations char **apple, char *orangel J, and char cherry If] same? Q su Can two different near pointers contain two different addresses but refer tothe same location in memory? Q a5 Can two different far pointers contain two different addresses but refer tothe same location in memory? 80 ‘Test Your C Skills Chapter 8: More About Pointers a1 Q a9 "What warning would be generated on compiling the following pro- Q a Can two different huge pointers contain two different addresses but ‘refer tothe same location in memory’ Q an ‘Would the following program give sny warning on compilation? ecluie'sdon" [How would you eliminate the warning generated on compiling the following program? = maint) Wouta te following program give any warning on compilation? Q 521 ‘tncudestgo ht mmain() i How would you obtain a far address from the segment and offset, fat pti =25505 addresses of a memory location? char ‘ps Q s22 How would you obwin segment and offset addresses from a far address of a memory location? 2 Test Your CSkills Q 328 Ina large data model (compact, large, huge) all pointers to data are ‘32 bits long, whereas ina small data model (iny, small, media) all, pointers are 16 bits long. Q 824 ‘A near pointer uses the contents of CS register (if the pointer is pointing to code) or contents of DS register (ithe pointers pointing {o data) for the segrnent part, whereas the offset partis stored in the 16-bit near pointer Q 525 ‘What would be the curpu of the following program? main) charter ‘a= cx00000120 char far“ = oxo0r00020, charfar‘c= 000120000; it(ansb) rin (He (azze] rin") it(b=re) ein ( elo"); i(abasarcatd>c) rin ("nbye"); Chapter 8: More About Pointers. 83 Q a2 fl char huge ‘a= 0400000120; char huge "b= 0x00100020; char huge ’e= 0x00120000; it(asbaka>ckab>c) Brit ("nye") A 32 Infiles "stdioh” and “stddet.h" A 33 ‘Because in small memory models the pointer is two bytes long ‘whereas i large memory models itis + bytes long. o Test Your C Skills A 84 For each pointer type (like say a char pointer) C defines a special pointer value which is guarenteed not to point to any object or function of that type. Usually, the null pointer constant used for representing a null poiner is the integer 0 A ss A nul pointer i a pointer which doesnt point anywhere, NULL macros se to eres the mall pier in sous ‘thas a value 0 associated with it. co ‘The ASCII NUL character has all its bits as O but doesn’t have any relationship with the nul! pointer. ‘The mull string is just another name for an empty string“ A 86 5 A 37 No, Oy income of pins shuld NULL and 0 be cans equal, NULL snd ot be ued when ober Lind aoe ‘Sere Een fought werk satalaycol pepsin ANS pena detlon ef e NULL maces [Te e705 “ich nares hatte NULL vl a Wo on poo ‘Chapier 8: More About Pointers 8S A ss 21 A 89 “A near pointer is 2 bytes long whereas afar and a huge pointer are 4 bytes long. A 810 ‘The Null Pointer Assignment erro is generated only in small and ‘medium memory models, This exror occurs in programs which at- ‘tempt to change the bottom of the data segment. ‘In Borland’s C or C+ compilers, Borland places four zero bytes at the bottom of the data segment followed by the Borland copyright notice "Borland C+ - Copyright 1991 Borland Int. In the small, and medium memory models, a nll pointer points to DS:0000. Thus ing a value to the memory referenced by this pointer will ‘overwrite the first zero byte inthe data segment, At program termina- tion, the four zeros and the copyright banner are checked, If either has been modified, then the Null Pointer Assignment error is generated. Note that the pointer may not wuly be null, ut may bea Wild pointer that references these key areas in the data segment. A su In the Integrated Development Environment set two watches on the Key memory locations mentioned in 8,10, These watches, and what, they should display inthe watch window, are *(char"j44es Botand C++ + Copyright 1991 Borland I" 86 Test Your C Skills (char‘j0 0.000000 ‘Ofcourse, the copyright banner will vary depending on your version ofthe Borland C/C++ compile, Step through your program using FX or FT and monitor these values inthe waich window. A the pint where one of them changes, you fave ust exeeted a Sateen tat ses a pointer hat as pot been rope ‘The most common cause of this error is probably declaring a pointer and then using i¢ before allocating memory for it. For example, comple the following program in the small memory model and execite it include “os fe ‘ince “t0." inctde “sting in) { char ‘py, “banner baer = (char *)MK_FP (_08, 4); pri | banner: banner): _tepy ("The word up saga’); rit pt = Spe (void fa) 0); Print (anne: is, banner); ) ‘One of the best debugging techniques for catching Null pointcr assignment errors is fo tur on all warning compiler messages, Ifthe above program is compiled with warnings tumed off, no warning ‘messages will be generated. However, if all warnings are turned on, both the strep) and pring calls using the ptr variable will geneiate .wamings. You shouldbe particularly suspicious ofany warnings that «8 variable might be used before being initialized, or ofa suspicious pointer assignment. (Chapter 8: More About Pointers 87 [Note that a Noll Pointer Assignment error is not generated in all, ‘models. Inthe compact, large and huge memory models far pointers fre used fr data, Therefore, null pointer will reference 0000:0000, lorthe base of system memory, andusing it will not cause corruption "ofthe key values atthe base ofthe data segment. Modifying the base of systemmemocy usually cases systemerash, however. Although it would be possible that a wild pointer would overwrite the key ‘values it would notindicateanll pointer. Inthe tiny memory mode, DS = CS =S. Therefore, using a all pointer will overwrite the beginning of the code segment. A sp “Yes, using a wild pointer that happens to reference the base area ofF the data segment may cause the same error since this would change the zeros of the copyright banner. Since data corruption or stack corruption could cause an otherwise-vald pointer tobe corrupted and, pint tothe base ofthe dats segment, any memory corruption could result inhi error being generated, Ifthe pointer used in the program ‘statement which corrupsthe key valves appears tohave been proper- ly initialized, place a watch on that pointer. Step through your ‘program again and watch forts value (address) to change. A 813 No A au No 58 Test Your C Stills A 815 ‘Yes A 516 No A a No A 38 ‘Yes, Suspicious pointer conversion in funetion mai A 319 Non-portable pointer assignment in function main. A 820 Use the typecast sr = ( char far * ) 0x88000000 ; A 821 rlude ds rman) har ‘seg = (cha) 8000; ‘har of = (char) 08000; Qhapier 8: More About Pointers 89 chartar’p; aN FP (209,011); char fr) oxBeD00000 seg: ( char") FP_SEG (ser); of | char*) FP_OFF (ser); 8.23 24 825 Bye 4b and refer to same location in memory sil the ist three fail because while comparing the far pointers wsing =— (and !=) full 32-it value i used and since the 42-bit values ane dierent the i ful. The lastifhowever gets satisfied, because while compar- NE using > (and >=, <, <= } only the offset value is used. for parsion. And the offst values of , band c are suc that he last liom i sate.

You might also like