You are on page 1of 15
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) )

You might also like