Você está na página 1de 67

C Questions

Note : All the programs are tested under Turbo C/C++ compilers. It is assumed that, Programs run under DOS en ironment, The underl!ing machine is an "#$ s!stem, Program is compiled using Turbo C/C++ compiler. The program output ma! depend on the in%ormation based on this assumptions &%or e"ample si'eo%&int( )) * ma! be assumed(. Predict the output or error&s( %or the %ollo+ing, -{ int const * p=5; printf("%d",++(*p)); } Answer: Compiler error, Cannot modi%! a constant alue. Explanation, p is a pointer to a .constant integer.. /ut +e tried to change the alue o% the .constant integer.. void main()

22
{

main() char s[ ]="man"; int i; for(i=0;s[ i ];i++) printf(" n%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]); }

Answer: mmmm aaaa nnnn Explanation, s0i1, 2&i+s(, 2&s+i(, i0s1 are all di%%erent +a!s o% e"pressing the same idea. 3enerall! arra! name is the base address %or that arra!. 4ere s is the base address. i is the inde" number/displacement %rom the base address. So, indirecting it +ith 2 is same as s0i1. i0s1 ma! be surprising. /ut in the case o% C it is same as s0i1.

22
{

main() f!oat m" = #$#; do%&!" 'o% = #$#; if(m"=='o%) printf("( !ov" )"); "!s" printf("( hat" )"); } Answer: I hate 5

Explanation, 6or %loating point numbers (%loat, double, long double) the alues cannot be predicted e"actl!. Depending on the number o% b!tes, the precession +ith o% the alue represented aries. 6loat ta7es 8 b!tes and long double ta7es 9: b!tes. So %loat stores :.; +ith less precision than long double. Rule of Thumb: <e er compare or at=least be cautious +hen using %loating point numbers +ith relational operators ()) , >, ?, ?), >),@) ) .

22

main() { static int var = 5; printf("%d ",var**); if(var) main(); } Answer: A8B*9 Explanation: Chen static storage class is gi en, it is initiali'ed once. The change in the alue o% a static ariable is retained e en bet+een the %unction calls. Dain is also treated li7e an! other ordinar! %unction, +hich can be called recursi el!.

22
{

main() int c[ ]={+$,,-$.,.,/$0,5}; int 1,*p=c,*2=c; for(1=0;135;1++) { printf(" %d ",*c); ++2; } for(1=0;135;1++){ printf(" %d ",*p); ++p; } }

Answer: ******B8$A Explanation: Initiall! pointer c is assigned to both p and q. In the %irst loop, since onl! q is incremented and not c , the alue * +ill be printed A times. In second loop p itsel% is incremented. So the alues * B 8 $ A +ill be printed.

22
{

main() "4t"rn int i; i=+0; printf("%d",i); } Answer: 5in6"r 7rror , 5nde%ined s!mbol EFiE Explanation:

e"tern storage class in the %ollo+ing declaration, extern int i; speci%ies to the compiler that the memor! %or i is allocated in some other program and that address +ill be gi en to the current program at the time o% lin7ing. /ut lin7er %inds that no other ariable o% name i is a ailable in an! other program +ith memor! space allocated %or it. 4ence a lin7er error has occurred .

22
{

main() int i=*#,1=*#,6=0,!=+,m; m=i++881++886++99!++; printf("%d %d %d %d %d",i,1,6,!,m); }

Answer: ::9B9 Explanation : Gogical operations al+a!s gi e a result o% 1 or 0 . And also the logical A<D &HH( operator has higher priorit! o er the logical OI &JJ( operator. So the e"pression Ki++ && j++ && k++ is e"ecuted %irst. The result o% this e"pression is : &=9 HH =9 HH : ) :(. <o+ the e"pression is : JJ * +hich e aluates to 9 &because OI operator al+a!s gi es 9 e"cept %or K: JJ :L combination= %or +hich it gi es :(. So the alue o% m is 9. The alues o% other ariables are also incremented b! 9.

22
{

main() char *p; printf("%d %d ",si:"of(*p),si:"of(p)); }

Answer: 98 Explanation: The si'eo%&( operator gi es the number o% b!tes ta7en b! its operand. EpE is a character pointer, +hich needs one b!te %or storing its alue &a character(. 4ence si'eo%&2p( gi es a alue o% 9. Since it needs t+o or %our b!tes to store the address o% the character pointer si'eo%&p( gi es * or 8 &depends on the machine(.

22
{

main() int i=-; s;itch(i) { d"fa%!t<printf(":"ro"); cas" #< printf("on""); &r"a6; cas" +<printf("t;o"); &r"a6; cas" -< printf("thr"""); &r"a6; } }

Answer : three Explanation : The de%ault case can be placed an!+here inside the loop. It is e"ecuted onl! +hen all other cases doesnEt match.

222 main() { printf("%4",*#33.); } Answer: %%%: or %%%%%%%: Explanation : =9 is internall! represented as all 9Es. Chen le%t shi%ted %our times the least signi%icant 8 bits are %illed +ith :Es. The M" %ormat speci%ier speci%ies that the integer alue be printed as a he"adecimal alue. 222 main() { char strin=[]=">"!!o ?or!d"; disp!a'(strin=); } void disp!a'(char *strin=) { printf("%s",strin=); } Answer: @ompi!"r 7rror < T!pe mismatch in redeclaration o% %unction displa! or +arning, con%licting t!pes %or Kdispla!L
note, pre ious implicit declaration o% Kdispla!L +as here Explanation : In third line, +hen the %unction displ ! is encountered, the compiler doesnEt 7no+ an!thing about the %unction displa!. It assumes the arguments and return t!pes to be integers, &+hich is the de%ault t!pe(. Chen it sees the actual %unction displ !" the arguments and t!pe contradicts +ith +hat it has assumed pre iousl!. 4ence a compile time error occurs. Carning +ill gone i% displa! %uction de%ine be%ore main&(. oid displa!&char 2string( N print%&.Ms.,string(O P main&( N char string01).4ello Corld.O displa!&string(O P

222 main() { int c=* *+; printf("c=%d",c); } Answer: c)*O Explanation: 4ere unar! minus &or negation( operator is used t+ice. Same maths rules applies, ie. minus 2 minus) plus. #ote: 4o+e er !ou cannot gi e li7e ==*. /ecause == operator can onl! be applied to ariables as a de$rement operator &eg., i==(. * is a constant and not a ariable. 222 Ad"fin" int char main() { int i=/5; printf("si:"of(i)=%d",si:"of(i)); } Answer: si'eo%&i()9 Explanation: Since the Qde%ine replaces the string int b! the macro $h r 222 main() { int i=#0; i=BiC#.; Drintf ("i=%d",i); } Answer: i): Explanation: In the e"pression %i&1' , <OT &@( operator has more precedence than K >L s!mbol. % is a unar! logical operator. @i &@9:( is : &not o% true is %alse(. :>98 is %alse &'ero(. 222 Ainc!%d"3stdio$hC main() { char s[]={EaE,E&E,EcE,E nE,EcE,E 0E}; char *p,*str,*str#; p=8s[-]; str=p; str#=s; printf("%d",++*p + ++*str#*-+); } Answer: RR

Explanation: p is pointing to character ESnE. str9 is pointing to character EaE ++2p. .p is pointing to ESnE and that is incremented b! one.. the ASCII alue o% ESnE is 9:, +hich is then incremented to 99. The alue o% ++2p is 99. ++2str9, str9 is pointing to EaE that is incremented b! 9 and it becomes EbE. ASCII alue o% EbE is ;#. <o+ per%orming &99 + ;# T B*(, +e get RR&.D.(O So +e get the output RR ,, .D. &Ascii is RR(.

222 Ainc!%d"3stdio$hC main() { int a[+][+][+] = { {#0,+,-,.}, {5,/,0,,} }; int *p,*2; p=8a[+][+][+]; *2=***a; printf("%d****%d",*p,*2); } Answer: Some3arbageUalue===9: Explanation: p)Ha0*10*10*1 !ou declare onl! t+o *D arra!s, but !ou are tr!ing to access the third *D&+hich !ou are not declared( it +ill print garbage alues. 2V)222a starting address o% a is assigned integer pointer. <o+ V is pointing to starting address o% a. I% !ou print 2V, it +ill print %irst element o% BD arra!. 222 Ainc!%d"3stdio$hC main() { str%ct 44 { int 4=-; char nam"[]="h"!!o"; }; str%ct 44 *s; printf("%d",s*C4); printf("%s",s*Cnam"); } Answer: Compiler Wrror Explanation: Xou should not initiali'e ariables in declaration 222 Ainc!%d"3stdio$hC main() { str%ct 44 { int 4; str%ct '' { char s;

str%ct 44 *p; }; str%ct '' *2; }; } Answer: Compiler Wrror Explanation: The structure !! is nested +ithin structure "". 4ence, the elements are o% !! are to be accessed through the instance o% structure "", +hich needs an instance o% !! to be 7no+n. I% the instance is created a%ter de%ining the structure the compiler +ill not 7no+ about the instance relati e to "". 4ence %or nested structure !! !ou ha e to declare member.

222 main() { printf(" na&"); printf(" &si"); printf(" rha"); } Answer: hai Explanation: Sn = ne+line Sb = bac7space Sr = line%eed 222 main() { int i=5; printf("%d%d%d%d%d%d",i++,i**,++i,**i,i); } Answer: 8AA8A
Explanation: The arguments in a %unction call are pushed into the stac7 %rom le%t to right. The e aluation is b! popping out %rom the stac7. and the e aluation is %rom right to le%t, hence the result.

222 Ad"fin" s2%ar"(4) 4*4 main() { int i; i = /.Fs2%ar"(.); printf("%d",i); } Answer: $8 Explanation:

the macro call sVuare&8( +ill substituted b! 828 so the e"pression becomes i ) $8/828 . Since / and 2 has eVual priorit! the e"pression +ill be e aluated as &$8/8(28 i.e. 9$28 ) $8

222 main() { char *p="hai fri"nds",*p#; p#=p; ;hi!"(*pB=E 0E) ++*p++; printf("%s %s",p,p#); } Answer: ibY@gsY%oet Explanation: ++2p++ +ill be parse in the gi en order 2p that is alue at the location currentl! pointed b! p +ill be ta7en ++2p the retrie ed alue +ill be incremented +hen O is encountered the location +ill be incremented that is p++ +ill be e"ecuted 4ence, in the +hile loop initial alue pointed b! p is KhL, +hich is changed to KiL b! e"ecuting ++2p and pointer mo es to point, KaL +hich is similarl! changed to KbL and so on. Similarl! blan7 space is con erted to K@L. Thus, +e obtain alue in p becomes ZibY@gsY%oet[ and since p reaches KS:L and p9 points to p thus p9doesnot print an!thing. 222 Ainc!%d" 3stdio$hC Ad"fin" a #0 main() { Ad"fin" a 50 printf("%d",a); } Answer: A:
Explanation: The preprocessor directi es can be rede%ined an!+here in the program. So the most recentl! assigned alue +ill be ta7en.

222 Ad"fin" c!rscr() #00 main() { c!rscr(); printf("%d n",c!rscr()); } Answer: 9:: Explanation: Preprocessor e"ecutes as a separate pass be%ore the e"ecution o% the compiler. So te"tual replacement o% clrscr&( to 9:: occurs. The input program to compiler loo7s li7e this , main&(

N 9::O print%&.MdSn.,9::(O P #ote: 9::O is an e"ecutable statement but +ith no action. So it doesnEt gi e an! problem

222 main() { printf("%p",main); } Answer: Some address +ill be printed. Explanation: 6unction names are Yust addresses &Yust li7e arra! names are addresses(. main&( is also a %unction. So the address o% %unction main +ill be printed. Mp in print% speci%ies that the argument is an address. The! are printed as he"adecimal numbers.
*R( main&( N clrscr&(O P clrscr&(O

Answer: <o output/error Explanation: The %irst clrscr&( occurs inside a %unction. So it becomes a %unction call. In the second clrscr&(O is a %unction declaration &because it is not inside an! %unction(. *#( enum colors N/GAC\,/G5W,3IWW<P main&( N print%&.Md..Md..Md.,/GAC\,/G5W,3IWW<(O return&9(O P Answer: :..9..* Explanation: enum assigns numbers starting %rom :, i% not e"plicitl! de%ined. *;( oid main&( N char %ar 2%arther,2%arthestO print%&.Md..Md.,si'eo%&%arther(,si'eo%&%arthest((O P

Answer: 8..* Explanation: the second pointer is o% char t!pe and not a %ar pointer B:( main&( N int i)8::,Y)B::O print%&.Md..Md.(O P Answer: 8::..B:: Explanation: print% ta7es the alues o% the %irst t+o assignments o% the program. An! number o% print%Es ma! be gi en. All o% them ta7e onl! the %irst t+o alues. I% more number o% assignments gi en in the program,then print% +ill ta7e garbage alues. main&( N char 2pO p).4ello.O print%&.McSn.,2H2p(O P Answer: 4 Explanation: 2 is a dere%erence operator H is a re%erence operator. The! can be applied an! number o% times pro ided it is meaning%ul. 4ere p points to the %irst character in the string .4ello.. 2p dere%erences it and so its alue is 4. Again H re%erences it to an address and 2 dere%erences it to the alue 4. main&( N int i)9O +hile &i?)A( N print%&.Md.,i(O i% &i>*( goto hereO i++O P P %un&( N here, print%&.PP.(O P Answer: Compiler error, 5nde%ined label EhereE in %unction main Explanation:

B9(

B*(

Gabels ha e %unctions scope, in other +ords The scope o% the labels is limited to %unctions . The label EhereE is a ailable in %unction %un&( 4ence it is not isible in %unction main. BB( main&( N static char names0A10*:1)N.pascal.,.ada.,.cobol.,.%ortran.,.perl.PO int iO char 2tO t)names0B1O names0B1)names081O names081)tO %or &i):Oi?)8Oi++( print%&.Ms.,names0i1(O P Answer: Compiler error, G alue reVuired in %unction main Explanation: Arra! names are pointer constants. So it cannot be modi%ied.

B8( main&(N char a09::1O a0:1)EaEOa0911)EbEOa0*1)EcEOa081)EdEO abc&a(O P abc&char a01(N a++O print%&.Mc.,2a(O a++O print%&.Mc.,2a(O P Explanation: The base address is modi%ied onl! in %unction and as a result a points to EbE then a%ter incrementing to EcE so bc +ill be printed. BA( main& ( N int a0 1 ) N9:,*:,B:,8:,A:P,Y,2pO %or&Y):O Y?AO Y++( N print%&ZMd[ ,2a(O a++O P p ) aO %or&Y):O Y?AO Y++( N print%&ZMd [ ,2p(O p++O P P Answer: Compiler error, l alue reVuired. Explanation:

Wrror is in line +ith statement a++. The operand must be an l alue and ma! be o% an! o% scalar t!pe %or the an! operator, arra! name onl! +hen subscripted is an l alue. Simpl! arra! name is a non=modi%iable l alue. B$( oid main&( N int i)AO print%&.Md.,i++ + ++i(O P Answer: Output Cannot be predicted e"actl!. Explanation: Side e%%ects are in ol ed in the e aluation o% i BR( N int i)AO print%&.Md.,i+++++i(O P Answer: Compiler Wrror Explanation: The e"pression i+++++i is parsed as i ++ ++ + i +hich is an illegal combination o% operators. B#( Qinclude?stdio.h> main&( N int i)9,Y)*O s+itch&i( N case 9, print%&.3OOD.(O brea7O case Y, print%&./AD.(O brea7O P P Answer: Compiler Wrror, Constant e"pression reVuired in %unction main. Explanation: The case statement can ha e onl! constant e"pressions &this implies that +e cannot use ariable names directl! so an error(. #ote: Wnumerated t!pes can be used in case statements. main&( N int iO print%&.Md.,scan%&.Md.,Hi((O // alue 9: is gi en as input here P Answer: oid main&(

B;(

9 Explanation: Scan% returns number o% items success%ull! read and not 9/:. 4ere 9: is gi en as input +hich should ha e been scanned success%ull!. So number o% items read is 9. 8:( Qde%ine %&g,g*( gQQg* main&( N int ar9*)9::O print%&.Md.,%& ar,9*((O P Answer: 9:: main&( N int i):O %or&Oi++Oprint%&.Md.,i(( O print%&.Md.,i(O P Answer: 9 Explanation: be%ore entering into the %or loop the chec7ing condition is .e aluated.. 4ere it e aluates to : &%alse( and comes out o% the loop, and i is incremented &note the semicolon a%ter the %or loop(. 8*( 8B( 88(

89(

main&( N print%&.Md., out(O P int out)9::O Answer: Compiler error, unde%ined s!mbol out in %unction main. Explanation: The rule is that a ariable is a ailable %or use %rom the point o% declaration. W en though a is a global ariable, it is not a ailable %or main. 4ence an error. main&( N e"tern outO print%&.Md., out(O P int out)9::O Answer: 9::

8A(

Explanation: This is the correct +a! o% +riting the pre ious program. 8$( main&( N sho+&(O P oid sho+&( N print%&.IEm the greatest.(O P Answer: Compier error, T!pe mismatch in redeclaration o% sho+. Explanation: Chen the compiler sees the %unction sho+ it doesnEt 7no+ an!thing about it. So the de%ault return t!pe &ie, int( is assumed. /ut +hen compiler sees the actual de%inition o% sho+ mismatch occurs since it is declared as oid. 4ence the error. The solutions are as %ollo+s, 9. declare oid sho+&( in main&( . *. de%ine sho+&( be%ore main&(. B. declare e"tern oid sho+&( be%ore the use o% sho+&(. main& ( N int a0*10B10*1 ) NNN*,8P,NR,#P,NB,8PP,NN*,*P,N*,BP,NB,8PPPO print%&ZMu Mu Mu Md Sn[,a,2a,22a,222a(O print%&ZMu Mu Mu Md Sn[,a+9,2a+9,22a+9,222a+9(O P Answer: 9::, 9::, 9::, * 998, 9:8, 9:*, B Explanation: The gi en arra! is a B=D one. It can also be ie+ed as a 9=D arra!. * 8 R # B 8 * * * B B 8 9:: 9:* 9:8 9:$ 9:# 99: 99* 998 99$ 99# 9*: 9** thus, %or the %irst print% statement a, 2a, 22a gi e address o% %irst element . since the indirection 222a gi es the alue. 4ence, the %irst line o% the output. %or the second print% a+9 increases in the third dimension thus points to alue at 998, 2a+9 increments in second dimension thus points to 9:8, 22a +9 increments the %irst dimension thus points to 9:* and 222a+9 %irst gets the alue at %irst location and then increments it b! 9. 4ence, the output. 8#( main& ( N static int a0 1 ) N:,9,*,B,8PO int 2p0 1 ) Na,a+9,a+*,a+B,a+8PO

8R(

int 22ptr ) pO ptr++O print%&ZSn Md Md Md[, ptr=p, 2ptr=a, 22ptr(O 2ptr++O print%&ZSn Md Md Md[, ptr=p, 2ptr=a, 22ptr(O 2++ptrO print%&ZSn Md Md Md[, ptr=p, 2ptr=a, 22ptr(O ++2ptrO print%&ZSn Md Md Md[, ptr=p, 2ptr=a, 22ptr(O P Answer: ### +++ ---.. Explanation: Get us consider the arra! and the t+o pointers +ith some address : 9:: 9:: 9::: 9 9:* 9:* 9::* ptr * 9:8 9:8 9::8 B 9:$ 9:$ 9::$ 8 9:# p 9:# 9::#

9::: *::: A%ter e"ecution o% the instruction ptr++ alue in ptr becomes 9::*, i% scaling %actor %or integer is * b!tes. <o+ ptr T p is alue in ptr T starting location o% arra! p, &9::* T 9:::( / &scaling %actor( ) 9, 2ptr T a ) alue at address pointed b! ptr T starting alue o% arra! a, 9::* has a alue 9:* so the alue is &9:* T 9::(/&scaling %actor( ) 9, 22ptr is the alue stored in the location pointed b! the pointer o% ptr ) alue pointed b! alue pointed b! 9::* ) alue pointed b! 9:* ) 9. 4ence the output o% the %irs print% is 9, 9, 9. A%ter e"ecution o% 2ptr++ increments alue o% the alue in ptr b! scaling %actor, so it becomes9::8. 4ence, the outputs %or the second print% are ptr T p ) *, 2ptr T a ) *, 22ptr ) *. A%ter e"ecution o% 2++ptr increments alue o% the alue in ptr b! scaling %actor, so it becomes9::$. 4ence, the outputs %or the third print% are ptr T p ) B, 2ptr T a ) B, 22ptr ) B. A%ter e"ecution o% ++2ptr alue in ptr remains the same, the alue pointed b! the alue is incremented b! the scaling %actor. So the alue in arra! p at location 9::$ changes %rom 9:$ to 9:#,. 4ence, the outputs %or the %ourth print% are ptr T p ) 9::$ T 9::: ) B, 2ptr T a ) 9:# T 9:: ) 8, 22ptr ) 8. 8;( main& ( N char 2VO int YO %or &Y):O Y?BO Y++( scan%&ZMs[ ,&V+Y((O

%or &Y):O Y?BO Y++( print%&ZMc[ ,2&V+Y((O %or &Y):O Y?BO Y++( print%&ZMs[ ,&V+Y((O P Explanation: 4ere +e ha e onl! one pointer to t!pe char and since +e ta7e input in the same pointer thus +e 7eep +riting o er in the same location, each time shi%ting the pointer alue b! 9. Suppose the inputs are DO5SW, TIAC\ and UIIT5AG. Then %or the %irst input suppose the pointer starts at location 9:: then the input one is stored as D O 5 S W S: Chen the second input is gi en the pointer is incremented as Y alue becomes 9, so the input is %illed in memor! starting %rom 9:9. D T I A C \ S: The third input starts %illing %rom the location 9:* D T U I I T 5 A G S: This is the %inal alue stored . The %irst print% prints the alues at the position V, V+9 and V+* ) D T U The second print% prints three strings starting %rom locations V, V+9, V+* i.e DTUIIT5AG, TUIIT5AG and UIIT5AG.

A:(

main& ( N oid 2 pO char ch ) KgL, 2cp ) Zgoo%![O int Y ) *:O p ) HchO print%&ZMc[, 2&char 2( p(O p ) HYO print%&ZMd[,2&int 2( p(O p ) cpO print%&ZMs[,&char 2( p + B(O P Answer: g*:%! Explanation: Since a oid pointer is used it can be t!pe casted to an! other t!pe pointer. p ) Hch stores address o% char ch and the ne"t statement prints the alue stored in p a%ter t!pe casting it to the proper data t!pe pointer. the output is KgL. Similarl! the output %rom second print% is K*:L. The third print% statement t!pe casts it to print the string %rom the 8th alue hence the output is K%!L.

A9( oid main&( N oid 2 O int integer)*O int 2i)HintegerO

)iO print%&.Md.,&int2(2 (O P Answer: Compiler Wrror. Ce cannot appl! indirection on t!pe oid2. Explanation: Uoid pointer is a generic pointer t!pe. <o pointer arithmetic can be done on it. Uoid pointers are normall! used %or, 9.Passing generic pointers to %unctions and returning such pointers. *.As a intermediate pointer t!pe. 5sed +hen the e"act pointer t!pe +ill be 7no+n at a later point o% time. A*( main & ( N static char 2s0 1 ) NZblac7[, Z+hite[, Z!ello+[, Z iolet[PO char 22ptr0 1 ) Ns+B, s+*, s+9, sP, 222pO p ) ptrO 22++pO print%&ZMs[,2==2++p + B(O P Answer: c7 Explanation: In this problem +e ha e an arra! o% char pointers pointing to start o% 8 strings. Then +e ha e ptr +hich is a pointer to a pointer o% t!pe char and a ariable p +hich is a pointer to a pointer to a pointer o% t!pe char. p hold the initial alue o% ptr, i.e. p ) s+B. The ne"t statement increment alue in p b! 9 , thus no+ alue o% p ) s+*. In the print% statement the e"pression is e aluated 2++p causes gets alue s+9 then the pre decrement is e"ecuted and +e get s+9 T 9 ) s . the indirection operator no+ gets the alue %rom the arra! o% s and adds B to the starting address. The string is printed starting %rom this position. Thus, the output is Kc7L. AB( main&( N int i, nO char 2" ) Zgirl[O n ) strlen&"(O 2" ) "0n1O %or&i):O i?nO ++i( N print%&ZMsSn[,"(O "++O P P Answer: &blan7 space( irl rl l

A8(

Explanation: 4ere a string &a pointer to char( is initiali'ed +ith a alue Zgirl[. The strlen %unction returns the length o% the string, thus n has a alue 8. The ne"t statement assigns alue at the nth location &KS:L( to the %irst location. <o+ the string becomes ZS:irl[ . <o+ the print% statement prints the string a%ter each iteration it increments it starting position. Goop starts %rom : to 8. The %irst time "0:1 ) KS:L hence it prints nothing and pointer alue is incremented. The second time it prints %rom "091 i.e Zirl[ and the third time it prints Zrl[ and the last time it prints Zl[ and the loop terminates. int i,YO %or&i):Oi?)9:Oi++( N Y+)AO assert&i?A(O P Answer: Iuntime error, Abnormal program termination. assert %ailed &i?A(, ?%ile name>,?line number> Explanation: asserts are used during debugging to ma7e sure that certain conditions are satis%ied. I% assertion %ails, the program +ill terminate reporting the same. A%ter debugging use, Qunde% <DW/53 and this +ill disable all the assertions %rom the source code. Assertion is a good debugging tool to ma7e use o%. main&( N int i)=9O +iO print%&.i ) Md, +i ) Md Sn.,i,+i(O P Answer: i ) =9, +i ) =9 Explanation: 5nar! + is the onl! dumm! operator in C. Chere=e er it comes !ou can Yust ignore it Yust because it has no e%%ect in the e"pressions &hence the name dumm! operator(.

AA(

A$(

Chat are the %iles +hich are automaticall! opened +hen a C %ile is e"ecuted] Answer: stdin, stdout, stderr &standard input,standard output,standard error(.

AR( +hat +ill be the position o% the %ile mar7er] a, %see7&ptr,:,SWW\FSWT(O b, %see7&ptr,:,SWW\FC5I(O Answer : a, The SWW\FSWT sets the %ile position mar7er to the starting o% the %ile. b, The SWW\FC5I sets the %ile position mar7er to the current position

o% the %ile. A#( main&( N char name09:1,s09*1O scan%&. S.M0^S.1S..,s(O P 4o+ scan% +ill e"ecute] Answer: 6irst it chec7s %or the leading +hite space and discards it.Then it matches +ith a Vuotation mar7 and then it reads all character upto another Vuotation mar7. Chat is the problem +ith the %ollo+ing code segment] +hile &&%gets&recei ing arra!,A:,%ileFptr(( @) WO6(O Answer & Explanation: %gets returns a pointer. So the correct end o% %ile chec7 is chec7ing %or @ ) <5GG. main&( N main&(O P Answer: Iuntime error , Stac7 o er%lo+. Explanation: main %unction calls itsel% again and again. Wach time the %unction is called its return address is stored in the call stac7. Since there is no condition to terminate the %unction call, the call stac7 o er%lo+s at runtime. So it terminates the program and results in an error. $9( main&( N char 2cptr,cO oid 2 ptr, O c)9:O ):O cptr)HcO ptr)H O print%&.McM .,c, (O P Answer: Compiler error &at line number 8(, si'e o% is 5n7no+n. Explanation: Xou can create a ariable o% t!pe oid 2 but not o% t!pe oid, since oid is an empt! t!pe. In the second line !ou are creating ariable ptr o% t!pe oid 2 and o% t!pe oid hence an error. main&( N char 2str9).abcd.O char str*01).abcd.O

A;(

$:(

$*(

print%&.Md Md Md.,si'eo%&str9(,si'eo%&str*(,si'eo%&.abcd.((O P Answer: 8AA Explanation: In %irst si'eo%, str9 is a character pointer so it gi es !ou the si'e o% the pointer ariable. In second si'eo% the name str* indicates the name o% the arra! +hose si'e is A &including the ES:E termination character(. The third si'eo% is similar to the second one. $B( main&( N char notO not)@*O print%&.Md.,not(O P Answer: : Explanation: @ is a logical operator. In C the alue : is considered to be the boolean alue 6AGSW, and an! non='ero alue is considered to be the boolean alue TI5W. 4ere * is a non='ero alue so TI5W. @TI5W is 6AGSW &:( so it prints :. Qde%ine 6AGSW =9 Qde%ine TI5W 9 Qde%ine <5GG : main&( N i%&<5GG( puts&.<5GG.(O else i%&6AGSW( puts&.TI5W.(O else puts&.6AGSW.(O P Answer: TI5W Explanation, The input program to the compiler a%ter processing b! the preprocessor is, main&(N i%&:( puts&.<5GG.(O else i%&=9( puts&.TI5W.(O else puts&.6AGSW.(O P Preprocessor doesnEt replace the alues gi en inside the double Vuotes. The chec7 b! i% condition is boolean alue %alse so it goes to else. In second i% =9 is boolean alue true hence .TI5W. is printed.

$8(

$A(

main&( N int 7)9O print%&.Md))9 is ..Ms.,7,7))9].TI5W.,.6AGSW.(O P Answer: 9))9 is TI5W Explanation: Chen t+o strings are placed together &or separated b! +hite=space( the! are concatenated &this is called as .stringi'ation. operation(. So the string is as i% it is gi en as .Md))9 is Ms.. The conditional operator& ], ( e aluates to .TI5W.. main&( N int !O scan%&.Md.,H!(O // input gi en is *::: i%& &!M8)): HH !M9:: @) :( JJ !M9:: )) : ( print%&.Md is a leap !ear.(O else print%&.Md is not a leap !ear.(O P Answer: *::: is a leap !ear Explanation: An ordinar! program to chec7 i% leap !ear or not. Qde%ine ma" A Qde%ine int arr90ma"1 main&( N t!pede% char arr*0ma"1O arr9 list)N:,9,*,B,8PO arr* name).name.O print%&.Md Ms.,list0:1,name(O P Answer: Compiler error &in the line arr9 list ) N:,9,*,B,8P( Explanation: arr* is declared o% t!pe arra! o% si'e A o% characters. So it can be used to declare the ariable name o% the t!pe arr*. /ut it is not the case o% arr9. 4ence an error. Rule of Thumb: Qde%ines are used %or te"tual replacement +hereas t!pede%s are used %or declaring ne+ t!pes. int i)9:O main&( N e"tern int iO N int i)*:O

$$(

$R(

$#(

N const olatile unsigned i)B:O print%&.Md.,i(O P print%&.Md.,i(O P print%&.Md.,i(O P Answer: B:,*:,9: Explanation: ENE introduces ne+ bloc7 and thus ne+ scope. In the innermost bloc7 i is declared as, const olatile unsigned +hich is a alid declaration. i is assumed o% t!pe int. So print% prints B:. In the ne"t bloc7, i has alue *: and so print% prints *:. In the outermost bloc7, i is declared as e"tern, so no storage space is allocated %or it. A%ter compilation is o er the lin7er resol es it to global ariable i &since it is the onl! ariable isible there(. So it prints iEs alue as 9:. $;( main&( N int 2YO N int i)9:O Y)HiO P print%&.Md.,2Y(O P Answer: 9: Explanation, The ariable i is a bloc7 le el ariable and the isibilit! is inside that bloc7 onl!. /ut the li%etime o% i is li%etime o% the %unction so it li es upto the e"it o% main %unction. Since the i is still allocated space, 2Y prints the alue stored in i since Y points i. main&( N int i)=9O =iO print%&.i ) Md, =i ) Md Sn.,i,=i(O P Answer: i ) =9, =i ) 9 Explanation: =i is e"ecuted and this e"ecution doesnEt a%%ect the alue o% i. In print% %irst !ou Yust print the alue o% i. A%ter that the alue o% the e"pression =i ) =&=9( is printed. Qinclude?stdio.h>

R:(

R9(

main&( N const int i)8O %loat YO Y ) ++iO print%&.Md M%., i,++Y(O P Answer, Compiler error Explanation, i is a constant. !ou cannot change the alue o% constant R*( Qinclude?stdio.h> main&( N int a0*10*10*1 ) N N9:,*,B,8P, NA,$,R,#P PO int 2p,2VO p)Ha0*10*10*1O 2V)222aO print%&.Md..Md.,2p,2V(O P Answer: garbage= alue..9 Explanation: p)Ha0*10*10*1 !ou declare onl! t+o *D arra!s. but !ou are tr!ing to access the third *D&+hich !ou are not declared( it +ill print garbage alues. 2V)222a starting address o% a is assigned integer pointer. no+ V is pointing to starting address o% a. i% !ou print 2V ,it +ill print %irst element o% BD arra!. Qinclude?stdio.h> main&( N register i)AO char Y01) .hello.O print%&.Ms Md.,Y,i(O P Answer: hello A Explanation, i% !ou declare i as register compiler +ill treat it as ordinar! integer and it +ill ta7e integer alue. i alue ma! be stored either in register or in memor!. main&( N int i)A,Y)$,'O print%&.Md.,i+++Y(O P Answer: 99 Explanation:

RB(

R8(

the e"pression i+++Y is treated as &i++ + Y( R$( struct aaaN struct aaa 2pre O int iO struct aaa 2ne"tO PO main&( N struct aaa abc,de%,ghi,Y7lO int ")9::O abc.i):Oabc.pre )HY7lO abc.ne"t)Hde%O de%.i)9Ode%.pre )HabcOde%.ne"t)HghiO ghi.i)*Oghi.pre )Hde%O ghi.ne"t)HY7lO Y7l.i)BOY7l.pre )HghiOY7l.ne"t)HabcO ")abc.ne"t=>ne"t=>pre =>ne"t=>iO print%&.Md.,"(O P Answer: * Explanation: abo e all statements %orm a double circular lin7ed listO abc.ne"t=>ne"t=>pre =>ne"t=>i this one points to .ghi. node the alue o% at particular node is *. struct point N int "O int !O PO struct point origin,2ppO main&( N pp)HoriginO print%&.origin is&MdMd(Sn.,&2pp(.",&2pp(.!(O print%&.origin is &MdMd(Sn.,pp=>",pp=>!(O P Answer: origin is&:,:( origin is&:,:( Explanation, pp is a pointer to structure. +e can access the elements o% the structure either +ith arro+ mar7 or +ith indirection operator. #ote: Since structure point is globall! declared " H ! are initiali'ed as 'eros. R#( main&( N int i)FlFabc&9:(O

RR(

print%&.MdSn.,==i(O P int FlFabc&int i( N return&i++(O P Answer: ; Explanation: return&i++( it +ill %irst return i and then increments. i.e. 9: +ill be returned. R;( main&( N char 2pO int 2VO long 2rO p)V)r):O p++O V++O r++O print%&.Mp...Mp...Mp.,p,V,r(O P Answer: :"9...:"8...:"8 Explanation: ++ operator +hen applied to pointers increments address according to their corresponding data=t!pes. main&( N char c)E E,",con ert&'(O getc&c(O i%&&c>)EaE( HH &c?)E'E(( ")con ert&c(O print%&.Mc.,"(O P con ert&'( N return '=B*O P Answer: Compiler error Explanation: declaration o% con ert and %ormat o% getc&( are +rong. main&int argc, char 22arg ( N print%&.enter the character.(O getchar&(O sum&arg 091,arg 0*1(O

#:(

#9(

P sum&num9,num*( int num9,num*O N return num9+num*O P Answer: Compiler error. Explanation: arg 091 H arg 0*1 are strings. The! are passed to the %unction sum +ithout con erting it to integer alues. #*( Q include ?stdio.h> int oneFd01)N9,*,BPO main&( N int 2ptrO ptr)oneFdO ptr+)BO print%&.Md.,2ptr(O P Answer, garbage alue Explanation: ptr pointer is pointing to out o% the arra! range o% oneFd. Q include?stdio.h> aaa&( N print%&.hi.(O P bbb&(N print%&.hello.(O P ccc&(N print%&.b!e.(O P main&( N int &2ptr0B1(&(O ptr0:1)aaaO ptr091)bbbO ptr0*1)cccO ptr0*1&(O P Answer, b!e Explanation: ptr is arra! o% pointers to %unctions o% return t!pe int.ptr0:1 is assigned to address o% the %unction aaa. Similarl! ptr091 and ptr0*1 %or bbb and ccc respecti el!. ptr0*1&( is in e%%ect o% +riting ccc&(, since ptr0*1 points to ccc.

#B(

#A(

Qinclude?stdio.h> main&( N 6IGW 2ptrO char iO ptr)%open&.'''.c.,.r.(O +hile&&i)%getch&ptr((@)WO6( print%&.Mc.,i(O P Answer: contents o% '''.c %ollo+ed b! an in%inite loop Explanation: The condition is chec7ed against WO6, it should be chec7ed against <5GG.

#$(

main&( N int i ):OY):O i%&i HH Y++( print%&.Md..Md.,i++,Y(O print%&.Md..Md,i,Y(O P Answer: :..: Explanation: The alue o% i is :. Since this in%ormation is enough to determine the truth alue o% the boolean e"pression. So the statement %ollo+ing the i% statement is not e"ecuted. The alues o% i and Y remain unchanged and get printed. main &( N int 7 ) AO i% &++7 ? A HH 7++/A JJ ++7 ?) #(O print% &.MdSn., 7(O P Answer: R main &( N int 7 ) AO i% &++7 ? A HH &7++/A JJ ++7 ?) #((O print% &.MdSn., 7(O P Answer: $ #R( main&( N int iO

i ) abc&(O print%&.Md.,i(O P abc&( N FA_ ) 9:::O P Answer: 9::: Explanation: <ormall! the return alue %rom the %unction is through the in%ormation %rom the accumulator. 4ere FA4 is the pseudo global ariable denoting the accumulator. 4ence, the alue o% the accumulator is set 9::: so the %unction returns alue 9:::. ##( int iO main&(N int tO %or & t)8Oscan%&.Md.,Hi(=tOprint%&.MdSn.,i(( print%&.Md==.,t==(O P // I% the inputs are :,9,*,B %ind the o/p Answer: 8==: B==9 *==* Explanation: Get us assume some ") scan%&.Md.,Hi(=t the alues during e"ecution +ill be, t i " 8 : =8 B 9 =* * * : main&(N int a) :Oint b ) *:Ochar " )9Ochar ! )9:O i%&a,b,",!( print%&.hello.(O P Answer: hello Explanation: The comma operator has associati it! %rom le%t to right. Onl! the rightmost alue is returned and the other alues are e aluated and ignored. Thus the alue o% last ariable ! is returned to chec7 in i%. Since it is a non 'ero alue i% becomes true so, .hello. +ill be printed. main&(N unsigned int iO %or&i)9Oi>=*Oi==( print%&.c aptitude.(O P

#;(

;:(

Explanation: i is an unsigned integer. It is compared +ith a signed alue. Since the both t!pes doesnEt match, signed is promoted to unsigned alue. The unsigned eVui alent o% =* is a huge alue so condition becomes %alse and control comes out o% the loop. ;9( In the %ollo+ing program add a statement in the %unction Z%un[ such that the address o% EaE gets stored in EYE. main&(N int 2 YO oid %un&int 22(O %un&HY(O P oid %un&int 227( N int a ):O /2 add a stmt here2/ P Answer: 27 ) Ha Explanation: The argument o% the %unction is a pointer to a pointer. ;*( Chat are the %ollo+ing notations o% de%ining %unctions 7no+n as] i. int abc&int a,%loat b( N /2 some code 2/ P ii. int abc&a,b( int aO %loat bO N /2 some code2/ P Answer: i. A<SI C notation ii. \ernighan H Iitche notation main&( N char 2pO p).MdSn.O p++O p++O print%&p=*,B::(O P Answer: B:: Explanation: The pointer points to M since it is incremented t+ice and again decremented b! *, it points to EMdSnE and B:: is printed.

;B(

;8(

;A(

%unc&a,b( int a,bO N return& a) &a))b( (O P main&( N int process&(,%unc&(O print%&.The alue o% process is Md @Sn .,process&%unc,B,$((O P process&p%, al9, al*( int &2p%( &(O int al9, al*O N return&&2p%( & al9, al*((O P Answer: The alue i% process is : @ Explanation: The %unction EprocessE has B parameters T one is a pointer to another %unction, * and B integers. Chen this %unction is in o7ed %rom main, the %ollo+ing substitutions %or %ormal parameters ta7e place, %unc %or p%, B %or al9 and $ %or al*. This %unction returns the result o% the operation per%ormed b! the %unction E%uncE. The %unction %unc has t+o integer parameters. The %ormal parameters are substituted as B %or a and $ %or b. since B is not eVual to $, a))b returns :. there%ore the %unction returns : +hich in turn is returned b! the %unction EprocessE. oid main&( N static int i)AO i%&==i(N main&(O print%&.Md .,i(O P P Answer: :::: Explanation: The ariable .I. is declared as static, hence memor! %or I +ill be allocated %or onl! once, as it encounters the statement. The %unction main&( +ill be called recursi el! unless I becomes eVual to :, and since main&( is recursi el! called, so the alue o% static I ie., : +ill be printed e er! time the control is returned.

;$(

;R( N

oid main&( int 7)ret&si'eo%&%loat((O print%&.Sn here alue is Md.,++7(O P int ret&int ret(

N ret +) *.AO return&ret(O P Answer: 4ere alue is R Explanation: The int ret&int ret(, ie., the %unction name and the argument name can be the same. 6irstl!, the %unction ret&( is called in +hich the si'eo%&%loat( ie., 8 is passed, a%ter the %irst e"pression the alue in ret +ill be $, as ret is integer hence the alue stored in ret +ill ha e implicit t!pe con ersion %rom %loat to int. The ret is returned in main&( it is printed a%ter and pre=increment. ;#( N char a01).9*B8AS:.O int i)strlen&a(O print%&.here in B MdSn.,++i(O P Answer: here in B $ Explanation: The char arra! EaE +ill hold the initiali'ed string, +hose length +ill be counted %rom : till the null character. 4ence the EiE +ill hold the alue eVual to A, a%ter the pre= increment in the print% statement, the $ +ill be printed. ;;( N unsigned gi eit)=9O int gotitO print%&.Mu .,++gi eit(O print%&.Mu Sn.,gotit)==gi eit(O P Answer: : $AABA Explanation: 9::( N int iO char a01).S:.O i%&print%&.MsSn.,a(( print%&.O7 here Sn.(O else print%&.6orget itSn.(O P Answer: O7 here Explanation: Print% +ill return ho+ man! characters does it print. 4ence printing a null character returns 9 +hich ma7es the i% statement true, thus .O7 here. is printed. oid main&( oid main&( oid main&(

9:9( N

oid main&( int i)i++,Y)Y++,7)7++O print%&ZMdMdMd[,i,Y,7(O

P Answer: 3arbage alues. Explanation: Gn id"ntifi"r is avai!a&!" to %s" in pro=ram cod" from th" point of its d"c!aration$ So e"pressions such as i ) i++ are alid statements. The i, Y and 7 are automatic ariables and so the! contain some garbage alue. Har&a=" in is =ar&a=" o%t (H(HI). 9:*( N static int i)i++, Y)Y++, 7)7++O print%&Zi ) Md Y ) Md 7 ) Md[, i, Y, 7(O P Answer: i)9Y)97)9 Explanation: Since static ariables are initiali'ed to 'ero b! de%ault. 9:B( N +hile&9(N i%&print%&.Md Sn.,print%&. Md Sn.((( brea7O else continueO P P Answer: 3arbage alues li7e, *:*$R#8 ; Explanation: The inner print% e"ecutes %irst to print some garbage alue. The print% returns no o% characters printed and this alue also cannot be predicted. Still the outer print% prints something and so returns a non='ero alue. So it encounters the brea7 statement and comes out o% the +hile statement. 9:8( main&( N unsigned int i)9:O +hile&i==>):( print%&.Mu .,i(O P Answer: 9: ; # R $ A 8 B * 9 : 8*;8;$R*;A 8*;8;$R*;8`.. Explanation: Since i is an unsigned integer it can ne er become negati e. So the e"pression i== >): +ill al+a!s be true, leading to an in%inite loop. oid main&( oid main&(

9:A(

Qinclude?conio.h> main&( N int ",!)*,',aO i%&")!M*( ')*O a)*O print%&.Md Md .,',"(O P Answer: 3arbage= alue : Explanation: The alue o% !M* is :. This alue is assigned to ". The condition reduces to i% &"( or in other +ords i%&:( and so ' goes uninitiali'ed. Thumb Rule: Chec7 all control paths to +rite bug %ree code. 9:$( main&( N int a09:1O print%&.Md.,2a+9=2a+B(O P Answer: 8 Explanation: 2a and =2a cancels out. The result is as simple as 9 + B ) 8 @ 9:R( Qde%ine prod&a,b( a2b main&( N int ")B,!)8O print%&.Md.,prod&"+*,!=9((O P Answer: 9: Explanation: The macro e"pands and e aluates to as, "+*2!=9 )> "+&*2!(=9 )> 9: main&( N unsigned int i)$A:::O +hile&i++@):(O print%&.Md.,i(O P Answer: 9 Explanation: <ote the semicolon a%ter the +hile statement. Chen the alue o% i becomes : it comes out o% +hile loop. Due to post=increment on i the alue o% i +hile printing is 9. 9:;( main&( N

9:#(

int i):O +hile&+&+i==(@):( i=)i++O print%&.Md.,i(O P Answer: =9 Explanation: )nar' + is th" on!' d%mm' op"rator in @. So it has no e%%ect on the e"pression and no+ the +hile loop is, +hile&i==@):( +hich is %alse and so brea7s out o% +hile loop. The alue T9 is printed due to the post=decrement operator. 99B( main&( N %loat %)A,g)9:O enumNi)9:,Y)*:,7)A:PO print%&.MdSn.,++7(O print%&.M%Sn.,%??*(O print%&.Ml%Sn.,%Mg(O print%&.Ml%Sn.,%mod&%,g((O P Answer: Gine no A, Wrror, G alue reVuired Gine no $, Cannot appl! le%tshi%t to %loat Gine no R, Cannot appl! mod to %loat Explanation: Wnumeration constants cannot be modi%ied, so !ou cannot appl! ++. /it=+ise operators and M operators cannot be applied on %loat alues. %mod&( is to %ind the modulus alues %or %loats as M operator is %or ints. 99:( main&( N int i)9:O oid pascal %&int,int,int(O %&i++,i++,i++(O print%&. Md.,i(O P oid pascal %&integer ,i,integer,Y,integer ,7( N +rite&i,Y,7(O P Answer: Compiler error, un7no+n t!pe integer Compiler error, undeclared %unction +rite Explanation: Pascal 7e!+ord doesnLt mean that pascal code can be used. It means that the %unction %ollo+s Pascal argument passing mechanism in calling the %unctions. 999( N print%&ZMd Md Md[,i, Y, 7(O P oid pascal %&int i,int Y,int 7(

oid cdecl %&int i,int Y,int 7( N print%&ZMd Md Md[,i, Y, 7(O P main&( N int i)9:O %&i++,i++,i++(O print%&. MdSn.,i(O i)9:O %&i++,i++,i++(O print%&. Md.,i(O P Answer: 9: 99 9* 9B 9* 99 9: 9B Explanation: Pascal argument passing mechanism %orces the arguments to be called %rom le%t to right. cdecl is the normal C argument passing mechanism +here the arguments are passed %rom right to le%t. 99*(. Chat is the output o% the program gi en belo+ main&( N signed char i):O %or&Oi>):Oi++( O print%&.MdSn.,i(O P Answer =9*# Explanation <otice the semicolon at the end o% the %or loop. The initial alue o% the i is set to :. The inner loop e"ecutes to increment the alue %rom : to 9*R &the positi e range o% char( and then it rotates to the negati e alue o% =9*#. The condition in the %or loop %ails and so comes out o% the %or loop. It prints the current alue o% i that is =9*#. 99B( main&( N unsigned char i):O %or&Oi>):Oi++( O print%&.MdSn.,i(O P Answer in%inite loop Explanation The di%%erence bet+een the pre ious Vuestion and this one is that the char is declared to be unsigned. So the i++ can ne er !ield negati e alue and i>): ne er becomes %alse so that it can come out o% the %or loop. 998( main&( N

char i):O %or&Oi>):Oi++( O print%&.MdSn.,i(O P Answer: /eha ior is implementation dependent. &3CC=it is signed int( Explanation: The detail i% the char is signed/unsigned b! de%ault is implementation dependent. I% the implementation treats the char to be signed b! de%ault the program +ill print T9*# and terminate. On the other hand i% it considers char to be unsigned b! de%ault, it goes to in%inite loop. Rule: Xou can +rite programs that ha e implementation dependent beha ior. /ut donEt +rite programs that depend on such beha ior. 99A( Is the %ollo+ing statement a declaration/de%inition. 6ind +hat does it mean] int &2"(09:1O Answer De%inition. " is a pointer to arra! o%&si'e 9:( integers. Appl! cloc7=+ise rule to %ind the meaning o% this de%inition. 99$(. Chat is the output %or the program gi en belo+ t!pede% enum errorT!peN+arning, error, e"ception,PerrorO main&( N error g9O g9)9O print%&.Md.,g9(O P Answer Compiler error, Dultiple declaration %or error Explanation The name error is used in the t+o meanings. One means that it is a enumerator constant +ith alue 9. The another use is that it is a t!pe name &due to t!pede%( %or enum errorT!pe. 3i en a situation the compiler cannot distinguish the meaning o% error to 7no+ in +hat sense the error is used, error g9O g9)errorO // +hich error it re%ers in each case] Chen the compiler can distinguish bet+een usages then it +ill not issue error &in pure technical terms, names can onl! be o erloaded in di%%erent name spaces(. Note, the e"tra comma in the declaration, enum errorT!peN+arning, error, e"ception,P is not an error. An e"tra comma is alid and is pro ided Yust %or programmerLs con enience. 99R( t!pede% struct errorNint +arning, error, e"ceptionOPerrorO main&( N error g9O

g9.error )9O print%&.Md.,g9.error(O P Answer 9 Explanation The three usages o% name errors can be distinguishable b! the compiler at an! instance, so alid &the! are in di%%erent name spaces(. T!pede% struct errorNint +arning, error, e"ceptionOPerrorO This error can be used onl! b! preceding the error b! struct 7e!+ord as in, struct error someWrrorO t!pede% struct errorNint +arning, error, e"ceptionOPerrorO This can be used onl! a%ter . &dot( or => &arro+( operator preceded b! the ariable name as in , g9.error )9O print%&.Md.,g9.error(O t!pede% struct errorNint +arning, error, e"ceptionOPerrorO This can be used to de%ine ariables +ithout using the preceding struct 7e!+ord as in, error g9O Since the compiler can per%ectl! distinguish bet+een these three usages, it is per%ectl! legal and alid. #ote This code is gi en here to Yust e"plain the concept behind. In real programming donLt use such o erloading o% names. It reduces the readabilit! o% the code. Possible doesnLt mean that +e should use it@ 99#( Qi%de% something int some):O Qendi% main&( N int thing ) :O print%&.Md MdSn., some ,thing(O P

Answer: Compiler error , unde%ined s!mbol some Explanation: This is a er! simple e"ample %or conditional compilation. The name something is not alread! 7no+n to the compiler ma7ing the declaration int some ( 0O e%%ecti el! remo ed %rom the source code. 99;( Qi% something )) : int some):O Qendi% main&( N int thing ) :O print%&.Md MdSn., some ,thing(O P

Answer :: Explanation This code is to sho+ that preprocessor e"pressions are not the same as the ordinar! e"pressions. I% a name is not 7no+n the preprocessor treats it to be eVual to 'ero. 9*:(. Chat is the output %or the %ollo+ing program main&( N int arr*D0B10B1O print%&.MdSn., &&arr*D))2 arr*D(HH&2 arr*D )) arr*D0:1(( (O P Answer 9 Explanation This is due to the close relation bet+een the arra!s and pointers. < dimensional arra!s are made up o% &<=9( dimensional arra!s. arr*D is made up o% a B single arra!s that contains B integers each . arr*D arr*D091 arr*D0*1 arr*D0B1

The name arr*D re%ers to the beginning o% all the B arra!s. 2arr*D re%ers to the start o% the %irst 9D arra! &o% B integers( that is the same address as arr*D. So the e"pression &arr*D )) 2arr*D( is true &9(. Similarl!, 2arr*D is nothing but 2&arr*D + :(, adding a 'ero doesnLt change the alue/meaning. Again arr*D0:1 is the another +a! o% telling 2&arr*D + :(. So the e"pression &2&arr*D + :( )) arr*D0:1( is true &9(. Since both parts o% the e"pression e aluates to true the result is true&9( and the same is printed. 9*9( oid main&( N i%&a: )) &unsigned int(=9( print%&ZXou can ans+er this i% !ou 7no+ ho+ alues are represented in memor![(O P )ns*er Xou can ans+er this i% !ou 7no+ ho+ alues are represented in memor! +xpl n tion a &tilde operator or bit=+ise negation operator( operates on : to produce all ones to %ill the space %or an integer. T9 is represented in unsigned alue as all 9Ls and so both are eVual. 9**( int s+ap&int 2a,int 2b( N

2a)2a+2bO2b)2a=2bO2a)2a=2bO P main&( N int ")9:,!)*:O s+ap&H",H!(O print%&.") Md ! ) MdSn.,",!(O P )ns*er " ) *: ! ) 9: +xpl n tion This is one +a! o% s+apping t+o alues. Simple chec7ing +ill help understand this. 9*B( main&( N char 2p ) Za!Vm[O print%&ZMc[,++2&p++((O P )ns*er, b main&( N int i)AO print%&.Md.,++i++(O P Answer: Compiler error, G alue reVuired in %unction main Explanation: ++i !ields an r alue. 6or post%i" ++ to operate an l alue is reVuired. #ote: An obYect is a contiguous region o% memor! storage. An l alue &pronounced, G alue( is an e"pression that re%ers to such an obYect. The original de%inition o% l alue re%erred to .an obYect that can appear on the le%t=hand side o% an assignment.. 4o+e er, const obYects are l alues, and !et the! cannot appear on the le%t=hand side o% an assignment. An e"pression that can appear in the right=hand side o% an e"pression &but not in the le%t=hand side o% an e"pression( is an r alue. n ) AO // n is an l alueO A is an r alue bu%0:1 ) EaEO //bu%0:1 is an l alue, EaE is an r alue string s9 ) .a., s* ) .b., sB ) .c.O // .a., .b., .c. are r alues s9 ) // l alue s* +sBO //s* and sB are l alues that are implicitl! con erted to r alues s9 ) string&.'.(O // temporaries are r alues 9*A( main&( N char 2p ) Za!Vm[O char cO c ) ++2p++O print%&ZMc[,c(O P

9*8(

Answer: b Explanation: There is no di%%erence bet+een the e"pression ++2&p++( and ++2p++. Parenthesis Yust +or7s as a isual clue %or the reader to see +hich e"pression is %irst e aluated. 9*$( int aaa&( Nprint%&Z4i[(OP int bbb&(Nprint%&Zhello[(OP in! ccc&(Nprint%&Zb!e[(OP main&( N int & 2 ptr0B1( &(O ptr0:1 ) aaaO ptr091 ) bbbO ptr0*1 )cccO ptr0*1&(O P )ns*er: b!e +xpl n tion, int &2 ptr0B1(&( sa!s that ptr is an arra! o% pointers to %unctions that ta7es no arguments and returns the t!pe int. /! the assignment ptr0:1 ) aaaO it means that the %irst %unction pointer in the arra! is initiali'ed +ith the address o% the %unction aaa. Similarl!, the other t+o arra! elements also get initiali'ed +ith the addresses o% the %unctions bbb and ccc. Since ptr0*1 contains the address o% the %unction ccc, the call to the %unction ptr0*1&( is same as calling ccc&(. So it results in printing .b!e.. 9*R( main&( N int i)AO print%&ZMd[,i)++i ))$(O P Answer: 1 Explanation: The e"pression can be treated as i ) &++i))$(, because )) is o% higher precedence than ) operator. In the inner e"pression, ++i is eVual to $ !ielding true&9(. 4ence the result. 9*#( main&( N char p0 1).MdSn.O p091 ) EcEO print%&p,$A(O P Answer: A

Explanation: Due to the assignment p091 ) KcL the string becomes, ZMcSn[. Since this string becomes the %ormat string %or print% and ASCII alue o% $A is KAL, the same gets printed. 9*;( oid & 2 abc& int, oid & 2de%( &( ( ( &(O

Ans+er, abc is a ptr to a %unction +hich ta7es * parameters . &a(. An integer ariable. &b(. A ptr to a %unction +hich returns oid. the return t!pe o% the %unction is oid. Explanation: Appl! the cloc7=+ise rule to %ind the result. 9B:( main&( N +hile &strcmp&Zsome[,[someS:[(( print%&ZStrings are not eVualSn[(O P Answer: <o output Explanation: Wnding the string constant +ith S: e"plicitl! ma7es no di%%erence. So Zsome[ and ZsomeS:[ are eVui alent. So, strcmp returns : &%alse( hence brea7ing out o% the +hile loop. 9B9( main&( N char str901 ) NKsL,LoL,LmL,LeLPO char str*01 ) NKsL,LoL,LmL,LeL,LS:LPO +hile &strcmp&str9,str*(( print%&ZStrings are not eVualSn[(O P Answer: ZStrings are not eVual[ ZStrings are not eVual[ `. `.&in%inite loop( Explanation: I% a string constant is initiali'ed e"plicitl! +ith characters, KS:L is not appended automaticall! to the string. Since str9 doesnLt ha e null termination, it treats +hate er the alues that are in the %ollo+ing positions as part o% the string until it randoml! reaches a KS:L. So str9 and str* are not the same, hence the result. 9B*( main&( N int i ) BO %or &Oi++):O( print%&ZMd[,i(O P

Answer: Compiler Wrror, G alue reVuired. Explanation: As +e 7no+ that increment operators return r alues and hence it cannot appear on the le%t hand side o% an assignment operation. 9BB( N int 2mptr, 2cptrO mptr ) &int2(malloc&si'eo%&int((O print%&ZMd[,2mptr(O int 2cptr ) &int2(calloc&si'eo%&int(,9(O print%&ZMd[,2cptr(O P Answer: garbage= alue : Explanation: The memor! space allocated b! malloc is uninitiali'ed, +hereas calloc returns the allocated memor! space initiali'ed to 'eros. 9B8( N static int iO +hile&i?)9:( &i>*(]i++,i==O print%&ZMd[, i(O P Answer: B*R$R //&*^9A =9( %or 3CC=== *98R8#B$8R //&*^B9=9( Explanation: Since i is static it is initiali'ed to :. Inside the +hile loop the conditional operator e aluates to %alse, e"ecuting i==. This continues till the integer alue rotates to positi e alue &B*R$R(. The +hile condition becomes %alse and hence, comes out o% the +hile loop, printing the i alue. 9BA( main&( N int i)9:,Y)*:O Y ) i, Y]&i,Y(]i,Y,YO print%&.Md Md.,i,Y(O P Answer: 9: 9: Explanation: The Ternar! operator & ] , ( is eVui alent %or i%=then=else statement. So the Vuestion can be +ritten as, i%&i,Y( N oid main&( oid main&(

i%&i,Y( Y ) iO else Y ) YO P else Y ) YO 9B$( 9. const char 2aO *. char2 const aO B. char const 2aO =Di%%erentiate the abo e declarations. Answer: 9. EconstE applies to char 2 rather than EaE & pointer to a constant char ( 2a)E6E , illegal a).4i. , legal *. EconstE applies to EaE rather than to the alue o% a &constant pointer to char ( 2a)E6E a).4i. B. Same as 9. 9BR( main&( N int i)A,Y)9:O i)iH)YHH9:O print%&.Md Md.,i,Y(O P Answer: 9 9: Explanation: The e"pression can be +ritten as i)&iH)&YHH9:((O The inner e"pression &YHH9:( e aluates to 9 because Y))9:. i is A. i ) AH9 is 9. 4ence the result. 9B#( main&( N int i)8,Y)RO Y ) Y JJ i++ HH print%&.XO5 CA<.(O print%&.Md Md., i, Y(O P Answer: 89 Explanation: Jh" &oo!"an "4pr"ssion n""ds to &" "va!%at"d on!' ti!! th" tr%th va!%" , legal , illegal

of th" "4pr"ssion is not 6no;n$ Y is not eVual to 'ero itsel% means that the e"pressionLs truth alue is 9. /ecause it is %ollo+ed b! JJ and tr%" 99 (an'thin=) =C tr%" ;h"r" (an'thin=) ;i!! not &" "va!%at"d$ So the remaining e"pression is not e aluated and so the alue o% i remains the same. Similarl! +hen HH operator is in ol ed in an e"pression, +hen an! o% the operands become %alse, the +hole e"pressionLs truth alue becomes %alse and hence the remaining e"pression +ill not be e aluated. fa!s" 88 (an'thin=) =C fa!s" ;h"r" (an'thin=) ;i!! not &" "va!%at"d$ 9B;( main&( N register int a)*O print%&.Address o% a ) Md.,Ha(O print%&.Ualue o% a ) Md.,a(O P Answer: Compier Wrror, EHE on register ariable Rule to Remember: & (address of ) operator cannot &" app!i"d on r"=ist"r varia&!"s$ 98:( main&( N %loat i)9.AO s+itch&i( N case 9, print%&.9.(O case *, print%&.*.(O de%ault , print%&.:.(O P P Answer: Compiler Wrror, s+itch e"pression not integral Explanation: K;itch stat"m"nts can &" app!i"d on!' to int"=ra! t'p"s$ 989( main&( N e"tern iO print%&.MdSn.,i(O N int i)*:O print%&.MdSn.,i(O P P Answer: Gin7er Wrror , 5nresol ed e"ternal s!mbol i Explanation: The identi%ier i is a ailable in the inner bloc7 and so using e"tern has no use in resol ing it. 98*( main&( N

int a)*,2%9,2%*O %9)%*)HaO 2%*+)2%*+)a+)*.AO print%&.SnMd Md Md.,a,2%9,2%*(O P Answer: 9$ 9$ 9$ Explanation: %9 and %* both re%er to the same memor! location a. So changes through %9 and %* ultimatel! a%%ects onl! the alue o% a. 98B( main&( N char 2p).3OOD.O char a0 1).3OOD.O print%&.Sn si'eo%&p( ) Md, si'eo%&2p( ) Md, strlen&p( ) Md., si'eo%&p(, si'eo%&2p(, strlen&p((O print%&.Sn si'eo%&a( ) Md, strlen&a( ) Md., si'eo%&a(, strlen&a((O P Answer: si'eo%&p( ) 8, si'eo%&2p( ) 9, strlen&p( ) 8 si'eo%&a( ) A, strlen&a( ) 8 Explanation: si'eo%&p( )> si'eo%&char2( )> * si'eo%&2p( )> si'eo%&char( )> 9 Similarl!, si'eo%&a( )> si'e o% the character arra! )> A ?h"n si:"of op"rator is app!i"d to an arra' it r"t%rns th" si:"of th" arra' and it is not the same as the si'eo% the pointer ariable. 4ere the si'eo%&a( +here a is the character arra! and the si'e o% the arra! is A because the space necessar! %or the terminating <5GG character should also be ta7en into account. 988( Qde%ine DID& arra!, t!pe( si'eo%&arra!(/si'eo%&t!pe( main&( N int arr09:1O print%&ZThe dimension o% the arra! is Md[, DID&arr, int((O P Answer: 9: Explanation: The si'e o% integer arra! o% 9: elements is 9: 2 si'eo%&int(. The macro e"pands to si'eo%&arr(/si'eo%&int( )> 9: 2 si'eo%&int( / si'eo%&int( )> 9:. 98A( int DID&int arra!01( N return si'eo%&arra!(/si'eo%&int (O P main&( N int arr09:1O print%&ZThe dimension o% the arra! is Md[, DID&arr((O

P Answer: 9 Explanation: Grra's cannot &" pass"d to f%nctions as ar=%m"nts and on!' th" point"rs can &" pass"d. So the argument is eVui alent to int 2 arra! &this is one o% the er! %e+ places +here 01 and 2 usage are eVui alent(. The return statement becomes, si'eo%&int 2(/ si'eo%&int( that happens to be eVual in this case. 98$( main&( N static int a0B10B1)N9,*,B,8,A,$,R,#,;PO int i,YO static 2p01)Na,a+9,a+*PO %or&i):Oi?BOi++( N %or&Y):OY?BOY++( print%&.MdStMdStMdStMdSn.,2&2&p+i(+Y(, 2&2&Y+p(+i(,2&2&i+p(+Y(,2&2&p+Y(+i((O P P Answer: 9 * B 8 A $ R # ; 9 8 R * A # B $ ; 9 * B 8 A $ R # ; 9 8 R * A # B $ ;

Explanation: 2&2&p+i(+Y( is eVui alent to p0i10Y1. 98R( main&( N oid s+ap&(O int ")9:,!)#O s+ap&H",H!(O print%&.")Md !)Md.,",!(O P oid s+ap&int 2a, int 2b( N 2a ^) 2b, 2b ^) 2a, 2a ^) 2bO P Answer: ")9: !)# Explanation: 5sing ^ li7e this is a +a! to s+ap t+o ariables +ithout using a temporar! ariable and that too in a single statement. Inside main&(, oid s+ap&(O means that s+ap is a %unction that ma!

ta7e an! number o% arguments &not no arguments( and returns nothing. So this doesnLt issue a compiler error b! the call s+ap&H",H!(O that has t+o arguments. This con ention is historicall! due to pre=A<SI st!le &re%erred to as \ernighan and Iitchie st!le( st!le o% %unction declaration. In that st!le, the s+ap %unction +ill be de%ined as %ollo+s, oid s+ap&( int 2a, int 2b N 2a ^) 2b, 2b ^) 2a, 2a ^) 2bO P +here the arguments %ollo+ the &(. So naturall! the declaration %or s+ap +ill loo7 li7e, oid s+ap&( +hich means the s+ap can ta7e an! number o% arguments. 98#( main&( N int i ) *ARO int 2iPtr ) HiO print%&.Md Md., 2&&char2(iPtr(, 2&&char2(iPtr+9( (O P Answer: 99 Explanation: The integer alue *AR is stored in the memor! as, :::::::9 :::::::9, so the indi idual b!tes are ta7en b! casting it to char 2 and get printed. 1',) -n .// main&( N int i ) 9998B$;O int 2iPtr ) HiO print%&.Md Md Md Md., 2&&char2(iPtr(, 2&&char2(iPtr+9(,2&&char2(iPtr+*(, 2&&char2(iPtr+B((O P 0utput: 9 9 9R : Explanation: ###.-/L is stor"d as 00000000 000#000# 0000000# 0000000#$M"m"m&"r that th" (NJ75 machin"s ar" Osma!!*"ndianP machin"s$ Kma!!*"ndian m"ans that th" !o;"r ord"r &'t"s ar" stor"d in th" hi=h"r m"mor' addr"ss"s and th" hi=h"r ord"r &'t"s ar" stor"d in !o;"r addr"ss"s$ 9A:( main&( N int i)B::O char 2ptr ) HiO 2++ptr)*O print%&.Md.,i(O

P Answer: AA$ Explanation: The integer alue B:: in binar! notation is, :::::::9 ::9:99::. It is stored in memor! &small=endian( as, ::9:99:: :::::::9. Iesult o% the e"pression 2+ +ptr ) * ma7es the memor! representation as, ::9:99:: ::::::9:. So the integer corresponding to it is ::::::9: ::9:99:: )> AA$. 9A9( Qinclude ?stdio.h> main&( N char 2 str ) .hello.O char 2 ptr ) strO char least ) 9*RO +hile &2ptr++( least ) &2ptr?least ( ]2ptr ,leastO print%&.Md.,least(O P Answer: : Explanation: A%ter KptrL reaches the end o% the string the alue pointed b! KstrL is KS:L. So the alue o% KstrL is less than that o% KleastL. So the alue o% KleastL %inall! is :. 9A*( Declare an arra! o% < pointers to %unctions returning pointers to %unctions returning pointers to characters] Answer: &char2&2(& (( &2ptr0<1(& (O main&( N

9AB(

struct student N char name0B:1O struct date dobO PstudO struct date N int da!,month,!earO PO scan%&.MsMdMdMd., stud.rollno, Hstudent.dob.da!, Hstudent.dob.month, Hstudent.dob.!ear(O P Answer: Compiler Wrror, 5nde%ined structure date Explanation: Inside the struct de%inition o% KstudentL the member o% t!pe struct date is gi en. The compiler doesnLt ha e the de%inition o% date structure &%or+ard re%erence is not allo+ed in C in this case( so it issues an error. 9A8( main&(

N struct dateO struct student N char name0B:1O struct date dobO PstudO struct date N int da!,month,!earO PO scan%&.MsMdMdMd., stud.name, Hstudent.dob.da!, Hstudent.dob.month, Hstudent.dob.!ear(O P Answer: Compiler Wrror, 5nde%ined structure date Explanation: Onl! declaration o% struct date is a ailable inside the structure de%inition o% KstudentL but to ha e a ariable o% t!pe struct date the de%inition o% the structure is reVuired. 9AA( There +ere 9: records stored in Zsome%ile.dat[ but the %ollo+ing program printed 99 names. Chat +ent +rong] oid main&( N struct student N char name0B:1, rollno0$1O PstudO 6IGW 2%p ) %open&Zsome%ile.dat[,[r[(O +hile&@%eo%&%p(( N %read&Hstud, si'eo%&stud(, 9 , %p(O puts&stud.name(O P P Explanation: %read reads 9: records and prints the names success%ull!. It +ill return WO6 onl! +hen %read tries to read another record and %ails reading WO6 &and returning WO6(. So it prints the last record again. A%ter this onl! the condition %eo%&%p( becomes %alse, hence comes out o% the +hile loop. <ote, 1in$lude 2stdio3h& si'eFt fr"ad& oid 2 restrict ptr, si'eFt si'e, si'eFt nmemb, 6IGW 2 restrict stream( f;rit"&const oid 2 restrict ptr, si'eFt si'e, si'eFt nmemb, 6IGW 2 restrict si'eFt stream( The %unction fre d reads nm"m& obYects, each si:" b!tes long, %rom the stream pointed to b! str"am, storing them at the location gi en b! ptr. 9A$( Is there an! di%%erence bet+een the t+o declarations, 9. int %oo&int 2arr01( and

*. int %oo&int 2arr0*1( Answer: <o Explanation: 6unctions can onl! pass pointers and not arra!s. The numbers that are allo+ed inside the 01 is Yust %or more readabilit!. So there is no di%%erence bet+een the t+o declarations. 9AR( Chat is the subtle error in the %ollo+ing code segment] oid %un&int n, int arr01( N int 2p):O int i):O +hile&i++?n( p ) Harr0i1O 2p ) :O P Answer & Explanation: I% the bod! o% the loop ne er e"ecutes p is assigned no address. So p remains <5GG +here 2p ): ma! result in problem &ma! rise to runtime error Z<5GG pointer assignment[ and terminate the program(. 9A#( Chat is +rong +ith the %ollo+ing code] int 2%oo&( N int 2s ) malloc&si'eo%&int(29::(O assert&s @) <5GG(O return sO P Answer & Explanation: assert macro should be used %or debugging and %inding out bugs. The chec7 s @) <5GG is %or error/e"ception handling and %or that assert shouldnLt be used. A plain i% and the corresponding remed! statement has to be gi en. 9A;( Chat is the hidden bug +ith the %ollo+ing statement] assert& al++ @) :(O Answer & Explanation: Assert macro is used %or debugging and remo ed in release ersion. In assert, the e"pression in ol es side=e%%ects. So the beha ior o% the code becomes di%%erent in case o% debug ersion and the release ersion thus leading to a subtle bug. Rule to Remember: QonPt %s" "4pr"ssions that hav" sid"*"ff"cts in ass"rt stat"m"nts$ 9$:( oid main&( N int 2i ) :"8::O // i points to the address 8:: 2i ) :O // set the alue o% memor! location pointed b! iO P Answer: 5nde%ined beha ior Segmentation %ault &In 3CC( Explanation:

The second statement results in unde%ined beha ior because it points to some location +hose alue ma! not be a ailable %or modi%ication. Jhis t'p" of point"r in ;hich th" non*avai!a&i!it' of th" imp!"m"ntation of th" r"f"r"nc"d !ocation is 6no;n as Eincomp!"t" t'p"E. 9$9( Qde%ine assert&cond( i%&@&cond(( S &%print%&stderr, .assertion %ailed, Ms, %ile Ms, line Md Sn.,Qcond,S FF6IGWFF,FFGI<WFF(, abort&(( oid main&( N int i ) 9:O i%&i)):( assert&i ? 9::(O else print%&.This statement becomes else %or i% in assert macro.(O P Ans+er, <o output Explanation: The else part in +hich the print% is there becomes the else %or i% in the assert macro. 4ence nothing is printed. The solution is to use conditional operator instead o% i% statement, Qde%ine assert&cond( &&cond(]&:(, &%print% &stderr, .assertion %ailed, S Ms, %ile Ms, line Md Sn.,Qcond, FF6IGWFF,FFGI<WFF(, abort&((( <ote, 4o+e er this problem o% Zmatching +ith nearest else[ cannot be sol ed b! the usual method o% placing the i% statement inside a bloc7 li7e this, Qde%ine assert&cond( N S i%&@&cond(( S &%print%&stderr, .assertion %ailed, Ms, %ile Ms, line Md Sn.,Qcond,S FF6IGWFF,FFGI<WFF(, abort&(( S P 9$*( Is the %ollo+ing code legal] struct a N int "O struct a bO P Ans+er, <o Explanation: Is it not legal %or a structure to contain a member that is o% the same t!pe as in this case. /ecause this +ill cause the structure declaration to be recursi e +ithout end. 9$B( Is the %ollo+ing code legal] struct a N

int "O struct a 2bO P Answer: Xes. Explanation: 2b is a pointer to t!pe struct a and so is legal. The compiler 7no+s, the si'e o% the pointer to a structure e en be%ore the si'e o% the structure is determined&as !ou 7no+ the pointer to an! t!pe is o% same si'e(. This t!pe o% structures is 7no+n as Ksel%=re%erencingL structure. 9$8( Is the %ollo+ing code legal] t!pede% struct a N int "O aT!pe 2bO PaT!pe Answer: <o Explanation: The t!pename aT!pe is not 7no+n at the point o% declaring the structure &%or+ard re%erences are not made %or t!pede%s(. 9$A( Is the %ollo+ing code legal] t!pede% struct a aT!peO struct a N int "O aT!pe 2bO PO Answer: Xes Explanation: The t!pename aT!pe is 7no+n at the point o% declaring the structure, because it is alread! t!pede%ined. 9$$( Is the %ollo+ing code legal] oid main&( N t!pede% struct a aT!peO aT!pe someUariableO struct a N int "O aT!pe 2bO PO P Answer: <o Explanation: Chen the declaration,

t!pede% struct a aT!peO is encountered bod! o% struct a is not 7no+n. This is 7no+n as Kincomplete t!pesL. 9$R( oid main&( N print%&Zsi'eo% & oid 2( ) Md SnZ, si'eo%& oid 2((O print%&Zsi'eo% &int 2( ) Md Sn[, si'eo%&int 2((O print%&Zsi'eo% &double 2( ) Md Sn[, si'eo%&double 2((O print%&Zsi'eo%&struct un7no+n 2( ) Md Sn[, si'eo%&struct un7no+n 2((O P Answer: gcc si'eo% & oid 2( ) * 8 si'eo% &int 2( ) * 8 si'eo% &double 2( ) * 8 si'eo%&struct un7no+n 2( ) * 8 Explanation: The pointer to an! t!pe is o% same si'e. char inputString09::1 ) N:PO To get string input %rom the 7e!board +hich one o% the %ollo+ing is better] 9( gets&inputString( *( %gets&inputString, si'eo%&inputString(, stdin(

9$#(

Answer & Explanation: The second one is better because gets&inputString( doesnEt 7no+ the si'e o% the string passed and so, i% a er! big input &here, more than 9:: chars( the charactes +ill be +ritten past the input string. Chen %gets is used +ith stdin per%orms the same operation as gets but is sa%e. <ote, char 2%gets&char 2s, int si'e, 6IGW 2stream(O // char 2gets&char 2s(O 9$;( Chich ersion do !ou pre%er o% the %ollo+ing t+o, 9( print%&ZMs[,str(O // or the more curt one *( print%&str(O

Answer & Explanation: Pre%er the %irst one. I% the str contains an! %ormat characters li7e Md then it +ill result in a subtle bug. 9R:( N int i)9:, Y)*O int 2ip) Hi, 2Yp ) HYO int 7 ) 2ip/2YpO print%&ZMd[,7(O P Answer: Compiler Wrror, Z5ne"pected end o% %ile in comment started in line A[. Explanation: oid main&(

The programmer intended to di ide t+o integers, but b! the Zm ximum mun$h[ rule, the compiler treats the operator seVuence / and 2 as /2 +hich happens to be the starting o% comment. To %orce +hat is intended b! the programmer, int 7 ) 2ip/ 2YpO // gi e space e"plicitl! separating / and 2 //or int 7 ) 2ip/&2Yp(O // put braces to %orce the intention +ill sol e the problem. 9R9( oid main&( N char chO %or&ch):Och?)9*ROch++( print%&ZMc Md SnZ, ch, ch(O P Answer: Implementation dependent Explanation: The char t!pe ma! be signed or unsigned b! de%ault. I% it is signed then ch++ is e"ecuted a%ter ch reaches 9*R and rotates bac7 to =9*#. Thus ch is al+a!s smaller than 9*R. 9R*( Is this code legal] int 2ptrO ptr ) &int 2( :"8::O Answer: Xes Explanation: The pointer ptr +ill point at the integer in the memor! location :"8::. main&( N char a081).4WGGO.O print%&.Ms.,a(O P Answer: Compiler error, Too man! initiali'ers Explanation: The arra! a is o% si'e 8 but the string constant reVuires $ b!tes to get stored. 9R8( main&( N char a081).4WGG.O print%&.Ms.,a(O P Answer: 4WGGMb@ab@b]]]baa@ Explanation: The character arra! has the memor! Yust enough to hold the string Z4WGG[ and doesnEt ha e enough space to store the terminating null character. So it prints the 4WGG correctl! and continues to print garbage alues till it accidentall! comes across a <5GG character.

9RB(

9RA(

main&( N int a)9:,2YO oid 27O Y)7)HaO Y++O 7++O print%&.Sn Mu Mu .,Y,7(O

P Answer: Compiler error, Cannot increment a oid pointer Explanation: Uoid pointers are generic pointers and the! can be used onl! +hen the t!pe is not 7no+n and as an intermediate address storage t!pe. <o pointer arithmetic can be done on it and !ou cannot appl! indirection operator &2( on oid pointers. 9R$( 9RR( Print% can be implemented b! using FFFFFFFFFF list. Answer: Uariable length argument lists 9R#( char 2some6un&( N char 2temp ) Zstring constant.O return tempO P int main&( N puts&some6un&((O P )ns*er: string constant Explanation, The program su%%ers no problem and gi es the output correctl! because the character constants are stored in code/data area and not allocated in stac7, so this doesnLt lead to dangling pointers. 9R;( char 2some6un9&( N char temp0 1 ) Zstring.O return tempO P char 2some6un*&( N char temp0 1 ) NKsL, KtL,LrL,LiL,LnL,LgLPO return tempO P int main&( N puts&some6un9&((O puts&some6un*&((O

P )ns*er: 3arbage alues. Explanation, /oth the %unctions su%%er %rom the problem o% dangling pointers. In some6un9&( temp is a character arra! and so the space %or it is allocated in heap and is initiali'ed +ith character string Zstring[. This is created d!namicall! as the %unction is called, so is also deleted d!namicall! on e"iting the %unction so the string data is not a ailable in the calling %unction main&( leading to print some garbage alues. The %unction some6un*&( also su%%ers %rom the same problem but the problem can be easil! identi%ied in this case. 9#:( The $omm oper tor &,( is a binar! operator that e aluates its %irst operand and discards the result, it then e aluates the second operand and returns this alue &and t!pe(. The comma operator has the lo+est precedence o% an! C operator, and acts as a seVuence point. The use o% the comma to7en as an oper tor is distinct %rom its use in %unction calls and de%initions, ariable declarations, enum declarations, and similar constructs, +here it acts as a sep r tor. In this e"ample, the di%%ering beha ior bet+een the second and third lines is due to the comma operator ha ing lo+er precendence than assignment.
int a)9, b)*, c)B, iO // comma acts as separator in this line, not as an operator i ) &a, b(O // stores b into i ... a)9, b)*, c)B, i)* i ) a, bO // stores a into i. WVui alent to &i ) a(, bO ... a)9, b)*, c)B, i)9 i ) &a +) *, a + b(O // increases a b! *, then stores a+b ) B+* into i ... a)B, b)*, c)B, i)A i ) a +) *, a + bO // increases a b! *, then stores a ) A into i ... a)A, b)*, c)B, i)A i ) a, b, cO // stores a into i ... a)A, b)*, c)B, i)A i ) &a, b, c(O // stores c into i ... a)A, b)*, c)B, i)B

9#9(

Crite the output o% this program

Q include Qde%ine calc &a, b( &a 2 b( / &a = b( oid main &( N int a ) *:, b ) 9:O print% &.MdSn., calc &a + 8, b =*((O P 0utput: Actual substitution is li7e this, Calc &*:+8, 9: =*( is calculated as %ollo+s &*:+8 2 9:=*( / &*:+8 = 9:=*( &*:+8:=*( / 9* A# / 9* ) 8.# Since it is printed in Md the ans is 8 9#*( oid %n &int, int(O

main &( N

int a ) AO print% &.Dain, Md MdSn., a++, ++a(O %n &a, a++(O P oid %n &int a, int b( N print% &.6n , a ) Md St b ) MdSn., a, b(O P )ns*er nd expl n tion: The solution depends on the implementation o% stac7. &Depends on OS( In some machines the arguments are passed %rom le%t to right to the stac7. In this case the result +ill be Dain, A R 6n, R R Other machines the arguments ma! be passed %rom right to le%t to the stac7. In that case the result +ill be &3CC( Dain, $ R 6n, # R i% the print% statement is, print% &.Dain, Md Md MdSn., a++, ++a ,++a(O then Dain, R # # 9#B( main &( N int 2a, 2s, iO s ) a ) &int 2( malloc & 8 2 si'eo% &int((O %or &i):O i?8O i++( 2&a+i( ) i 2 9:O print% &.MdSn., 2s++(O print% &.MdSn., &2s(++(O print% &.MdSn., 2s(O print% &.MdSn., 2++s(O print% &.MdSn., ++2s(O P )ns*er nd expl n tion: The output +ill be, : 9: 99 *: *9 2s++ )> 2&s++( 2++s )> 2&++s( ++2s )> ++&2s( 9#8( oid %n &int(O

static int al ) AO main &( N +hile & al ==( %n & al(O print% &.St Md., al(O P oid %n &int al9( N static int al ) :O %or &O al ? AO al ++( print% &.MdSn., al(O P )ns*er nd expl n tion: : 9 * B 8 =9 9#A( main &( N t!pede% struct N int aO int bO int cO char chO int dO P "!'O t!pede% union N "!' _O char ! 09::1O P abcO print% &.si'eo% "!' ) Md si'eo% abc ) MdSn., si'eo% &"!'(, si'eo% &abc((O P )ns*er nd expl n tion: The output o% this program is purel! depends on the processor architecuture. I% the si'eo% integer is 8 b!tes and the si'e o% character is 9 b!te &In some computers(, the output +ill be si'eo% "!' ) *: si'eo% abc ) 9:: The output can be generali'ed to some e"tent as %ollo+s, si'eo% "!' ) 8 2 si'eo% &int( + 9 2 si'eo% &char( + padding b!tes si'eo% abc ) 9:: 2 si'eo% &char( + padding b!tes To 7eep the structures/unions b!te aligned, some padding b!tes are added in bet+een the structure %ields. In this e"ample B b!tes are padded bet+een E char chE and Eint dE %ields. The unused b!tes are called holes. To understand more about padding b!tes

&holes( tr! ar!ing the %ield t!pes o% the structures and see the output. t!pede% struct N int aO int bO int cO char chO char ch9O int dO P "!'O si'eo%&"!'()*: t!pede% struct N int aO int bO int cO char chO char ch9O P "!'O si'eo%&"!'()9$ 9#$( main &( N t!pede% union N int aO char b 09:1O %loat cO P 5nionO 5nion ", ! ) N9::PO ".a ) A:O strcp! &".b, .hello.(O ".c ) *9.A:O print% &.5nion *, Md Ms M%Sn., ".a, ".b, ".c(O print% &.5nion X, Md Ms M%Sn., !.a, !.b, !.c(O P )ns*er nd expl n tion: This is the problem about 5nions. 5nions are similar to structures but it di%%ers in some +a!s. 5nions can be assigned onl! +ith one %ield at an! time. In this case, unions " and ! can be assigned +ith an! o% the one %ield a or b or c at one time. During initiali'ation o% unions it ta7es the alue &+hate er assigned( onl! %or the %irst %ield. So, The statement ! ) N9::P initiali'es the union ! +ith %ield a ) 9::. In this e"ample, all %ields o% union " are assigned +ith some alues. /ut at an! time onl! one o% the union %ields can be assigned. So, %or the union " the %ield c is assigned as *9.A:. Thus, The output +ill be 5nion *, ** ** *9.A: 5nion X, 9:: ** ** &** re%ers unpredictable results(

9#R( main &( N struct Data N int aO int bO P ! 081 ) N9, 9:, B, B:, *, *:, 8, 8:PO struct Data 2" ) !O int iO %or &i):O i?8O i++( N "=>a ) "=>b, ++"++=>bO print% &.Md MdSt., ! 0i1. a, ! 0i1. b(O P P )ns*er nd expl n tion: The pointer " points to the same location +here ! is stored. So, The changes in ! re%lect in ". ++"++=>b ) ++&"++=>b( The output +ill be, 9: 99 B: B9 *: *9 8: 89

9##( main &(N int 2a, iO a ) &int 2( malloc &9:2si'eo% &int((O %or &i):O i?9:O i++( 2&a + i( ) i 2 iO %or &i):O i?9:O i++( print% &.MdSt., 2a++(O %ree &a(O P )ns*er nd expl n tion: This program +ill %ault &Demor! %ault/segmentation %ault(. Can !ou predict +h!] Iemo e the statement E%ree &a(OL %rom the program, then e"ecute the program. It +ill run. It gi es the results correctl!. Chat causes E%ree &a(E to generate %ault] cust trace the address location o% pointer ariable EaE. The ariable EaE is incremented inside the E%or loopE. Out side the E%or loopE the ariable EaE +ill point to EnullE. Chen the %ree &( call is made, it +ill %ree the data area %rom the baseFaddress &+hich is passed as the argument o% the %ree call( up to the length o% the data allocated pre iousl!. In this case, %ree &( tries to %ree the length o% 9: 2si'eo% &int( %rom the base pointer location passed as the argument to the %ree call, +hich is EnullE in this case. Thus, it generates memor! %ault. 9#;( Qinclude?stdio.h>

main&( Nchar p01).String.O int "):O i%&p)).String.( N print%&.Pass 9,Md.,si'eo%&p((O i%&p0si'eo%&p(=*1))EgE( print%&.Pass *.(O else print%&.6ail *.(O P else N print%&.6ail 9, Md.,si'eo%&p( (O i%&p0si'eo%&p(=*1))EgE( print%&. Pass *.(O else print%&. 6ail *.(O P P )ns: 6ail 9, R Pass * i% u replace the statement Echar p01).String. E +ith Echar 2p).String. E then output is Pass 9,8 6ail * 9;:( Qinclude?stdio.h> main&( Nchar 2p0*1)N.String.,.and.PO char p901).ram.O print%&.Ms Mc MsSn.,p9,2&p0:1+9(,p091(O unsigned int ")=9O int !O ! ) a:O i%&" )) !( print%&.same Sn.(O else print%&.not same Sn.(O P )ns: ram t and same 9;9( main&( Nint i):O %or&i):Oi?*:Oi++( Ns+itch&i(

N case :,i+)AO case 9,i+)*O case A,i+)AO de%ault, i+)8O brea7OP print%&.Md,.,i(O P enum N a)=9, b) 8,c,d,ePO print%&.Md.,e(O P )ns: 9$,*9,R #L+) 74p!ain (nt"rna! !in6a="$ Internal lin7age means that all declarations o% the identi%ier +ithin one source %ile re%er to a single entit! but declarations o% the same identi%ier in other source %iles re%er to di%%erent entities. #L-) @an th" forma! param"t"r to a f%nction &" d"c!ar"d staticR <o, because arguments are al+a!s passed on the stac7 to support recursion. #L.) ?hat is an !va!%"R Something that can appear on the le%t side o% the .). sign, it identi%ies a place +here the result can be stored. 6or e"ample, in the eVuation a)b+*A, a is an l alue. In the eVuation b+*A)a. b+*A cannot be used as an l alue, because it does not identi%! a speci%ic place. 4ence the abo e assignment is illegal. #L5) 7v"r' "4pr"ssion that is an !va!%", is a!so an rva!%"$ (s th" r"v"rs" tr%"R <o, l alue denotes a place in the computerEs memor!. An r alue denotes a alue, so it can onl! be used on the right hand side o% an assignment. #L/) ?hat happ"ns if indir"ction is p"rform"d on a N)55 point"rR On some machines the indirection accesses the memor! location 'ero. On other machines indirection on a <5GG pointer cause a %ault that terminate the program. 4ence the result is implementation dependent. #L0) (s th" stat"m"nt !"=a!R d=#0**d$ Illegal because it speci%ies that an integer Vuantit! &9:=2d( be stored in a pointer ariable

#L,) ?hat do"s th" &"!o; indicat"R


int *f%nc(void)

oid indicates that there arenEt an! arguments. there is one argument o% t!pe oid.
Gns;"r< a

#LL) ?hat ar" data t'p" modifi"rsR To e"tend the data handling po+er, C adds 8 modi%iers +hich ma! onl! be applied to char and int. The! are namel! signed, unsigned, long and short. Although long ma! also be applied to double. +00) (nt"rpr"t th" m"anin= of th" fo!!o;in=$ B. Zab[,[a+b[ 8. Z++t[ Ans+er, .ab.,.a+b.=>open a binar! %ile %or appending .++t. =>create a te"t %ile %or reading and +riting. +0#) ?hat is N)55 in th" cont"4t of fi!"sR In using %iles, i% an! error occurs, a <5GG pointer is returned. +0+) ?hat is M"=ist"r stora=" c!assR It concerns itsel% +ith storing data in the registers o% the microprocessor and not in memor!. The alue o% the ariable doesnEt ha e to be loaded %reshl! %rom memor! e er! time. ItEs important to reali'e that this a reVuest to the compiler and not a directi e. The compiler ma! not be able to do it. Since the registers are normall! o% 9$ bits long, +e can use the register storage class %or ints and charEs. +0-) ?hat is an ass"rtion stat"m"ntR The! are actuall! macros. The! test statements !ou pass to them and i% the statement is %alse, the! halt the program and in%orm !ou that the assertion %ailed. It is de%ined in the header %ile ?assert.h>. +0.) Dars" int *(*(*(*a&c)())[/])(); abc is a pointer to a %unction returning a pointer to arra! o% pointer to %unctions returning pointer to integer. *:A( S+apping t+o ariables +ithout using a temp ariable 4sin5 pointers

Qinclude ?stdio.h> oid change&int 2,int2(O int main &( N int a)*,b)AO print%&./e%ore , a)Md,b)MdSn.,a,b(O change&Ha,Hb(O print%&.A%ter , a)Md,b)MdSn.,a,b(O return :O P oid change&int 2a,int 2b(N 2a +) 2bO 2b ) 2a=2bO 2a ) 2a=2bO P Results /e%ore , a)*,b)A A%ter , a)A,b)* 6 kin5 use of 6 $ro

Qinclude ?stdio.h> Qde%ine SCAP&",!( " ^) !, ! ^) ", " ^) ! int main &( N int a)*,b)AO print%&./e%ore , a)Md,b)MdSn.,a,b(O SCAP&a,b(O //simpl! a^)b^)a^)bO print%&.A%ter , a)Md,b)MdSn.,a,b(O return :O P Results: /e%ore , a)*,b)A A%ter , a)A,b)* *:$( Crite a %unction re str &( = +hich re erses the gi en string in the same string bu%%er using pointers. &i.e.( Should not use e"tra bu%%ers %or cop!ing the re erse string. )ns: Qinclude?stdio.h> A( int main&( N char cO c)getchar&(O i%&c@) E.E( //dot is to terminate +hen u r %inished gi en the string char b! char/ main&(O//calling main recursi el! putchar&c(O

return :O P /( char 2re Fstr &char 2str( N char 2s ) str, 2e ) s + strlen &s( =9O char 2t ) .Yun7.O /2 to be sa%e = con%orming +ith A<SI C std 2/ Chile &s ? e( N2t ) 2eO 2e== ) 2sO 2s++ ) 2tOP Ieturn &str(O P char 2strFre &char 2str( N int len ) strlen &str(,i):,Y)len/*O len==O +hile &i ? Y( N 2&str+i( ^)2 &str+len(^)2 &str+i(^)2 &str+len(O i++O len==O P return &str(O P main &int argc, char 22arg ( N print% &.9st method, MsSn., re Fstr &arg 091((O print% &.*nd method, MsSn., strFre &arg 091((O P /2 Another +a! o% doing this 2/ oid Istring& char 2str,int len( Nint iO %or& i ) :O i ? &len/*(O i++( N str0i1 ^) str0len=i=91O str0len=i=91 ^) str0i1O str0i1 ^) str0len=i=91O P P int main& oid ( N char str01 ) .m! string.O print%&.Actual string is 0Ms1Sn., str(O Istring&str,strlen&str((O print%&.Ie ersed string is 0Ms1Sn., str(O P main&(N char a09:1,iO int len)9O print%&. Wnter string .(O %gets&a,;,stdin(O

len ) strlen&a(O %or&i): O i?&len/*( O i++(N a0i1)a0i1+a0len=*1O a0len=*1)a0i1=a0len=*1O a0i1)a0i1=a0len=*1O len==O P print%&.Sn Ie erse string +ith n/* comple"it! Ms.,a(O return :O P *:R( Crite a program to print the series * po+er ", +here " >) : &9, *, 8, #, 9$...( +ithout using C math librar! and arithmetic operators &i.e. 2, /, +, = and math.h are not allo+ed( )ns: Qinclude?stdio.h> oid main &( N int iO %or &i):O i? 9:O i++( print% &.MdSt., * ?? i(O P *:#( Crite a general s+ap macro in C, A macro, +hich can s+ap an! t!pe o% data &i.e. int, char, %loat, struct, etc...( )ns: Qinclude?stdio.h> /2 3eneric S+ap macro2/ Qde%ine s+ap &a, b, t!pe( Nt!pe t ) aO a ) bO b ) tO P /2 Ueri%ication routines 2/ main &( N int a)9:, b )*:O %loat e)9:.:, % ) *:.:O char 2" ) .string9., 2! ) .string*.O t!pede% struct Nint aO char s0*:1O P stO st s9 ) NA:, .struct9.P, s* ) N9::, .struct*.PO s+ap &a, b, int(O print% &.Md Md Sn., a, b(O s+ap &e, %, %loat(O print% &.M% M% Sn., e, %(O s+ap &", !, char 2(O print% &.Ms MsSn., ", !(O s+ap &s9, s*, st(O print% &.S9, Md Ms StS*, Md MsSn., s9.a, s9.s, s*.a, s*.s(O ptrFs+ap &(O P ptrFs+ap &( N int 2a, 2bO %loat 2c, 2dO a ) &int 2( malloc &si'eo% &int((O

b ) &int 2( malloc &si'eo% &int((O 2a ) 9:O 2b ) *:O s+ap &a, b, int 2(O print% &.Md MdSn., 2a, 2b(O c ) &%loat 2( malloc&si'eo%&%loat((O d ) &%loat 2( malloc&si'eo%&%loat((O 2c ) 9:.:9O 2d ) *:.:*O s+ap &c, d, %loat 2(O print% &.M% M%Sn., 2c, 2d(O P *:;( main &( N int a)B, b ) AO print% &Ha0.Xa@ 4ello@ 4o+ is this] MsSn.1, Hb0.Yun7/super.1(O print% &Ha 0.C4AT Mc Mc Mc Mc Mc Mc @Sn.1, 90.this.1, *0.beaut!.1,:0.tool.1,:0.is.1,B0.sensiti e.1,80.CCCCCC.1(O P )ns: In C +e can inde" an arra! in t+o +a!s. 6or e"ample loo7 in to the %ollo+ing lines int a 0B1 ) N9:, *:, B:, 8:PO In this e"ample inde")B o% arra! EaE can be represented in * +a!s. 9( a 0B1 and *( B 0a1 i.e.( a 0B1 ) B 0a1 ) 8: W"tend the same logic to this problem. Xou +ill get the output as %ollo+s 4ello@ ho+ is this] Super That is C *9:( int main&( N int a)B,b)$O print%&.Md/2 Md 2/ .,a,b(O P )ns*er: B/2 $ 2/

Você também pode gostar