Programming Questions
Programming Questions
s
printf(“I love U”);
else
or
printf(“I hate U”);
Find the output or error(s) for the following Programs:
}
1. void main()
Answer:
{
ct
I hate U
int const * p=5;
Explanation:
printf("%d",++(*p));
For floating point numbers (float, double, long double) the values cannot be predicted exactly.
ru
} Depending on the number of bytes, the precession with of the value represented varies. Float takes
Answer: 4 bytes and long double takes 10 bytes. So float stores 0.9 with less precision than long double.
Compiler error: Cannot modify a constant value. Rule of Thumb:
Explanation: Never compare or at-least be cautious when using floating point numbers with relational
st
p is a pointer to a “constant integer”. But we tried to change the value of the “constant operators (== , >, <, <=, >=,!= ) .
integer”. 4. main()
2. main()
In
{
{ static int var = 5;
char s[ ]=“man”; printf(“%d ”,var--);
int i; if(var)
for(i=0;s[ i ];i++)
E main();
printf(“\n%c%c%c%c”,s[ i ],*(s+i),*(i+s),i[s]); }
} Answer:
AT
Answer: 54321
mmmm Explanation:
aaaa When static storage class is given, it is initialized once. The change in the value of a static
nnnn variable is retained even between the function calls. Main is also treated like any other ordinary
Explanation: function, which can be called recursively.
G
s[i], *(i+s), *(s+i), i[s] are all different ways of expressing the same idea. Generally array 5. main()
name is the base address for that array. Here s is the base address. i is the index number/displacement {
int c[ ]={2.8,3.4,4,6.7,5};
int j,*p=c,*q=c; }
for(j=0;j<5;j++) { Answer:
printf(“ %d ”,*c); 00131
++q; } Explanation:
for(j=0;j<5;j++){ Logical operations always give a result of 1 or 0. And also the logical AND (&&) operator
printf(“ %d ”,*p); has higher priority over the logical OR (||) operator. So the expression ‘i++ && j++ &&
k++’ is executed first. The result of this expression is 0(-1 && -1 && 0 = 0). Now the
++p; }
expression is 0 || 2 which evaluates to 1 (because OR operator always gives 1 except for ‘0
s
} || 0’ combination- for which it gives 0). So the value of m is 1. The values of other variables
are also incremented by 1.
or
Answer: 8. main()
2222223465 {
Explanation: char *p;
ct
Initially pointer c is assigned to both p and q. In the first loop, since only q is incremented and printf(“%d %d ”,sizeof(*p),sizeof(p));
not c , the value 2 will be printed 5 times. In second loop p itself is incremented. So the values 2 3 4 }
6 5 will be printed.
ru
6. main()
Answer:
{
12
extern int i;
Explanation:
st
i=20;
The sizeof() operator gives the number of bytes taken by its operand. P is a character
printf(“%d”,i); pointer, which needs one byte for storing its value (a character). Hence sizeof(*p) gives a value of 1.
} Since it needs two bytes to store the address of the character pointer sizeof(p) gives 2.
In
9. main()
Answer: {
Linker Error : Undefined symbol ‘_i’ int i=3;
Explanation: switch(i)
E
extern storage class in the following declaration, {
extern int i; default:printf(“zero”);
specifies to the compiler that the memory for i is allocated in some other program and that
AT
case 1: printf(“one”);
address will be given to the current program at the time of linking. But linker finds that no break;
other variable of name i is available in any other program with memory space allocated for
case 2:printf(“two”);
it. Hence a linker error has occurred.
break;
7. main()
case 3: printf("three");
{
G
break;
int i=-1,j=-1,k=0,l=2,m;
}
m=i++&&j++&&k++||l++;
}
printf(“%d %d %d %d %d”,i,j,k,l,m);
Answer: printf(“c=%d”,c);
three }
Explanation: Answer:
The default case can be placed anywhere inside the loop. It is executed only when all other c=2;
cases doesn’t match. Explanation:
10. main() Here unary minus (or negation) operator is used twice. Same maths rules applies, ie., minus
{ * minus= plus.
s
printf(“%x”,-1<<4); Note:
} However you cannot give like --2. Because -- operator can only be applied to variables as
or
Answer: a decrement operator (eg., i--). 2 is a constant and not a variable.
fff0
Explanation : 13. #define int char
ct
-1 is internally represented as all 1’s. When left shifted four times the least significant 4 bits main()
are filled with 0’s. The %x format specifier specifies that the integer value be printed as a hexadecimal {
value. int i=65;
ru
printf(“sizeof(i)=%d”,sizeof(i));
11. main() }
{ Answer:
char string[]=“Hello World”;
st
sizeof(i)=1
display(string); Explanation:
} Since the #define replaces the string int by the macro char
In
void display(char *string)
{ 14. main()
printf(“%s”,string); {
} int i=10;
E
Answer: i=!i>14;
Compiler Error : Type mismatch in redeclaration of function display printf (“i=%d”,i);
Explanation: }
AT
In third line, when the function display is encountered, the compiler doesn’t know anything Answer:
about the function display. It assumes the arguments and return types to be integers, (which is the
i=0
default type). When it sees the actual function display, the arguments and type contradicts with
what it has assumed previously. Hence a compile time error occurs. Explanation:
In the expression !i>14, NOT (!) operator has more precedence than ‘ >’ symbol. ! is a
G
unary logical operator. !i (!10) is 0 (not of true is false). 0>14 is false (zero).
12. main()
15. #include<stdio.h>
{
main()
int c=- -2;
{
char s[]={‘a’,‘b’,‘c’,‘\n’,‘c’,'\0'}; struct xx
char *p,*str,*str1; {
p=&s[3]; int x=3;
str=p; char name[]=“hello”;
str1=s; };
printf(“%d”,++*p + ++*str1-32); struct xx *s;
} printf(“%d”,s->x);
s
Answer: printf(“%s”,s->name);
77 }
or
Explanation: Answer:
p is pointing to character ‘\n’. str1 is pointing to character ‘a’ ++*p. “p is pointing to ‘\n’ and Compiler Error
that is incremented by one.” the ASCII value of ‘\n’ is 10, which is then incremented to 11. The value Explanation:
ct
of ++*p is 11. ++*str1, str1 is pointing to ‘a’ that is incremented by 1 and it becomes ‘b’. ASCII value
You should not initialize variables in declaration.
of ‘b’ is 98.
Now performing (11 + 98 – 32), we get 77(“M”);
18. #include<stdio.h>
ru
So we get the output 77 :: “M” (ASCII is 77).
main()
16. #include<stdio.h>
{
main()
struct xx
{
st
{
int a[2][2][2] = { {10,2,3,4}, {5,6,7,8} };
int x;
int *p,*q;
struct yy
In
p=&a[2][2][2];
{
*q=***a;
char s;
printf(“%d----%d”,*p,*q);
struct xx *p;
}
};
E
Answer:
struct yy *q;
SomeGarbageValue---1
};
Explanation:
AT
}
p=&a[2][2][2] you declare only two 2D arrays, but you are trying to access the third
2D(which you are not declared) it will print garbage values. *q=***a starting address of a is assigned Answer:
integer pointer. Now q is pointing to starting address of a. If you print *q, it will print first element of Compiler Error
3D array. Explanation:
The structure yy is nested within structure xx. Hence, the elements are of yy are to be
G
17. #include<stdio.h> accessed through the instance of structure xx, which needs an instance of yy to be known. If the
main() instance is created after defining the structure the compiler will not know about the instance relative
to xx. Hence for nested structure yy you have to declare member.
{
19. main() 22. main()
{ {
printf(“\nab”); char *p=“hai friends”,*p1;
printf(“\bsi”); p1=p;
printf(“\rha”); while(*p!=‘\0’) ++*p++;
} printf(“%s %s”,p,p1);
Answer: }
s
hai Answer:
Explanation: ibj!gsjfoet
or
\n - newline Explanation:
\b - backspace ++*p++ will be parse in the given order
\r - linefeed *p that is value at the location currently pointed by p will be taken
ct
++*p the retrieved value will be incremented
20. main() when ; is encountered the location will be incremented that is p++ will be executed
{ Hence, in the while loop initial value pointed by p is ‘h’, which is changed to ‘i’ by executing
ru
int i=5; ++*p and pointer moves to point, ‘a’ which is similarly changed to ‘b’ and so on. Similarly blank
space is converted to ‘!’. Thus, we obtain value in p becomes “ibj!gsjfoet” and since p reaches ‘\0’
printf(“%d%d%d%d%d%d”,i++,i--,++i,--i,i);
and p1 points to p thus p1does not print anything.
}
st
Answer:
23. #include <stdio.h>
45545
#define a 10
Explanation:
In
main()
The arguments in a function call are pushed into the stack from left to right. The evaluation
{
is by popping out from the stack and the evaluation is from right to left, hence the result.
#define a 50
printf(“%d”,a);
21. #define square(x) x*x
E
}
main()
Answer:
{
50
AT
int i;
Explanation:
i = 64/square(4);
The preprocessor directives can be redefined anywhere in the program. So the most recently
printf(“%d”,i);
assigned value will be taken.
}
Answer:
G
s
replacement of clrscr() to 100 occurs. The input program to compiler looks like this : printf(“%d..%d..%d”,BLACK,BLUE,GREEN);
main() return(1);
or
{ }
100; Answer:
printf(“%d\n”,100); 0..1..2
ct
} Explanation:
Note: enum assigns numbers starting from 0, if not explicitly defined.
100; is an executable statement but with no action. So it doesn’t give any problem.
ru
28. void main()
25. main() {
{ char far *farther,*farthest;
st
printf(“%p”,main); printf(“%d..%d”,sizeof(farther),sizeof(farthest));
} }
Answer: Answer:
In
Some address will be printed. 4..2
Explanation: Explanation:
Function names are just addresses (just like array names are addresses). The second pointer is of char type and not a far pointer.
main() is also a function. So the address of function main will be printed. %p in printf
E
specifies that the argument is an address. They are printed as hexadecimal numbers. 29. main()
{
26. main()
AT
int i=400,j=300;
{ printf(“%d..%d”);
clrscr(); }
} Answer:
clrscr(); 400..300
G
Explanation:
Answer: printf takes the values of the first two assignments of the program. Any number of printf’s
No output/error may be given. All of them take only the first two values. If more number of assignments
given in the program, then printf will take garbage values.
30. main() 32. main()
{ {
char *p; static char names[5][20]={“pascal”,“ada”,“cobol”,“fortran”,“perl”};
p=“Hello”; int i;
printf(“%c\n”,*&*p); char *t;
} t=names[3];
Answer: names[3]=names[4];
s
H names[4]=t;
Explanation: for (i=0;i<=4;i++)
or
* is a dereference operator & is a reference operator. They can be applied any number of printf(“%s”,names[i]);
times provided it is meaningful. Here p points to the first character in the string “Hello”. *p }
dereferences it and so its value is H. Again & references it to an address and * dereferences
Answer:
it to the value H.
ct
Compiler error: Lvalue required in function main
Explanation:
31. main()
Array names are pointer constants. So it cannot be modified.
ru
{
int i=1;
33. void main()
while (i<=5)
{
{
st
int i=5;
printf(“%d”,i);
printf(“%d”,i++ + ++i);
if (i>2)
}
In
goto here;
Answer:
i++;
Output Cannot be predicted exactly.
}
Explanation:
}
Side effects are involved in the evaluation of i.
fun()
E
{
34. void main()
here:
AT
{
printf(“PP”);
int i=5;
}
printf(“%d”,i+++++i);
Answer:
}
Compiler error: Undefined label ‘here’ in function main.
Answer:
G
Explanation:
Compiler Error
Labels have functions scope, in other words the scope of the labels is limited to functions.
The label ‘here’ is available in function fun() hence it is not visible in function main. Explanation:
The expression i+++++i is parsed as i ++ ++ + i which is an illegal combination of operators.
35. #include<stdio.h> printf(“%d”,f(var,12));
main() }
{ Answer:
int i=1,j=2; 100
switch(i) 38. main()
{ {
case 1: printf(“GOOD”); int i=0;
s
break; for(;i++;printf(“%d”,i)) ;
case j: printf(“BAD”); printf(“%d”,i);
or
break; }
} Answer:
} 1
ct
Answer: Explanation:
Compiler Error: Constant expression required in function main. Before entering into the for loop the checking condition is “evaluated”. Here it evaluates
Explanation: to 0 (false) and comes out of the loop, and i is incremented (note the semicolon after
ru
the for loop).
The case statement can have only constant expressions (this implies that we cannot
use variable names directly so an error).
Note: 39. #include<stdio.h>
st
Enumerated types can be used in case statements. main()
{
36. main() char s[]={‘a’,‘b’,‘c’,‘\n’,‘c’,‘\0’};
In
{ char *p,*str,*str1;
int i; p=&s[3];
printf(“%d”,scanf(“%d”,&i)); // value 10 is given as input here str=p;
} str1=s;
E
Answer: printf(“%d”,++*p + ++*str1-32);
1 }
Answer:
AT
Explanation:
Scanf returns number of items successfully read and not 1/0. Here 10 is given as input M
which should have been scanned successfully. So number of items read is 1. Explanation:
p is pointing to character ‘\n’.str1 is pointing to character ‘a’ ++*p meAnswer: “p is
37. #define f(g,g2) g##g2 pointing to ‘\n’ and that is incremented by one.” the ASCII value of ‘\n’ is 10. Then it
G
s
} Linker error: undefined symbol ‘_i’.
struct xx *s=malloc(sizeof(struct xx)); Explanation:
or
printf(“%d”,s->x); extern declaration specifies that the variable i is defined somewhere else. The compiler
printf(“%s”,s->name); passes the external variable to be resolved by the linker. So compiler doesn’t find an
error. During linking the linker searches for the definition of i. Since it is not found the
}
linker flags an error.
ct
Answer:
Compiler Error
43. main()
Explanation:
ru
{
Initialization should not be done for structure members inside the structure declaration
printf(“%d”, out);
}
41. #include<stdio.h>
int out=100;
st
main()
Answer:
{
Compiler error: undefined symbol out in function main.
struct xx
In
Explanation:
{
The rule is that a variable is available for use from the point of declaration. Even
int x; though a is a global variable, it is not available for main. Hence an error.
struct yy
{
E 44. main()
char s; {
struct xx *p; extern out;
AT
} printf(“%d”, out);
struct yy *q; }
} int out=100;
} Answer:
Answer:
G
100
Compiler Error Explanation:
Explanation: This is the correct way of writing the previous program.
In the end of nested structure yy a member have to be declared.
45. main() for the second printf a+1 increases in the third dimension thus points to value at 114,
{ *a+1 increments in second dimension thus points to 104, **a +1 increments the first
dimension thus points to 102 and ***a+1 first gets the value at first location and then
show();
increments it by 1. Hence, the output.
}
void show()
47. main( )
{
{
printf(“I’m the greatest”);
int a[ ] = {10,20,30,40,50},j,*p;
s
}
for(j=0; j<5; j++)
Answer:
or
{
Compier error: Type mismatch in redeclaration of show.
printf(“%d” ,*a);
Explanation:
a++;
When the compiler sees the function show it doesn’t know anything about it. So the
}
ct
default return type (ie, int) is assumed. But when compiler sees the actual definition of
show mismatch occurs since it is declared as void. Hence the error. p = a;
The solutions are as follows: for(j=0; j<5; j++)
ru
1. declare void show() in main(). {
2. define show() before main(). printf(“%d ” ,*p);
3. declare extern void show() before the use of show(). p++;
}
st
46. main( ) }
{ Answer:
In
int a[2][3][2] = {{{2,4},{7,8},{3,4}},{{2,2},{2,3},{3,4}}}; Compiler error: lvalue required.
printf(“%u %u %u %d \n”,a,*a,**a,***a); Explanation:
printf(“%u %u %u %d \n”,a+1,*a+1,**a+1,***a+1); Error is in line with statement a++. The operand must be an lvalue and may be of any
of scalar type for the any operator, array name only when subscripted is an lvalue.
}
Simply array name is a non-modifiable lvalue.
E
Answer:
100, 100, 100, 2
48. main( )
114, 104, 102, 3
AT
{
Explanation:
static int a[ ] = {0,1,2,3,4};
The given array is a 3-D one. It can also be viewed as a 1-D array.
int *p[ ] = {a,a+1,a+2,a+3,a+4};
2 4 7 8 3 4 2 2 2 3 3 4 int **ptr = p;
100 102 104 106 108 110 112 114 116 118 120 122 ptr++;
G
thus, for the first printf statement a, *a, **a give address of first element since the printf(“\n %d %d %d”, ptr-p, *ptr-a, **ptr);
indirection ***a gives the value. Hence, the first line of the output. *ptr++;
printf(“\n %d %d %d”, ptr-p, *ptr-a, **ptr);
*++ptr; 49. main( )
printf(“\n %d %d %d”, ptr-p, *ptr-a, **ptr); {
++*ptr; char *q;
printf(“\n %d %d %d”, ptr-p, *ptr-a, **ptr); int j;
} for (j=0; j<3; j++) scanf(“%s” ,(q+j));
Answer: for (j=0; j<3; j++) printf(“%c” ,*(q+j));
111 for (j=0; j<3; j++) printf(“%s” ,(q+j));
s
222 }
333 Explanation:
or
444 Here we have only one pointer to type char and since we take input in the same pointer thus
Explanation: we keep writing over in the same location, each time shifting the pointer value by 1. Suppose the
inputs are MOUSE, TRACK and VIRTUAL. Then for the first input suppose the pointer starts at
Let us consider the array and the two pointers with some address
location 100 then the input one is stored as
ct
a
M O U S E \0
0 1 2 3 4
When the second input is given the pointer is incremented as j value becomes 1, so the input
ru
100 102 104 106 108 is filled in memory starting from 101.
p
M T R A C K \0
100 102 104 106 108
st
The third input starts filling from the location 102
1000 1002 1004 1006 1008
M T V I R T U A L \0
ptr
This is the final value stored.
In
1000
The first printf prints the values at the position q, q+1 and q+2 = M T V
2000
The second printf prints three strings starting from locations q, q+1, q+2
After execution of the instruction ptr++ value in ptr becomes 1002, if scaling factor for
i.e., MTVIRTUAL, TVIRTUAL and VIRTUAL.
integer is 2 bytes. Now ptr – p is value in ptr – starting location of array p, (1002 – 1000) / (scaling
E
factor) = 1, *ptr – a = value at address pointed by ptr – starting value of array a, 1002 has a value
102 so the value is (102 – 100)/(scaling factor) = 1, **ptr is the value stored in the location pointed 50. main( )
by the pointer of ptr = value pointed by value pointed by 1002 = value pointed by 102 = 1. Hence the {
AT
output of the firs printf is 1, 1, 1. void *vp;
After execution of *ptr++ increments value of the value in ptr by scaling factor, so it char ch = ‘g’, *cp = “goofy”;
becomes1004. Hence, the outputs for the second printf are ptr – p = 2, *ptr – a = 2, **ptr = 2.
int j = 20;
After execution of *++ptr increments value of the value in ptr by scaling factor, so it
vp = &ch;
becomes1004. Hence, the outputs for the third printf are ptr – p = 3, *ptr – a = 3, **ptr = 3.
printf(“%c”, *(char *)vp);
G
After execution of ++*ptr value in ptr remains the same, the value pointed by the value is
incremented by the scaling factor. So the value in array p at location 1006 changes from 106 10 108. vp = &j;
Hence, the outputs for the fourth printf are ptr – p = 1006 – 1000 = 3, *ptr – a = 108 – 100 = 4, **ptr printf(“%d”,*(int *)vp);
= 4. vp = cp;
printf(“%s”,(char *)vp + 3); {
} printf(“%s\n”,x);
Answer: x++;
g20fy }
Explanation: }
Since a void pointer is used it can be type casted to any other type pointer. vp = &ch stores Answer:
address of char ch and the next statement prints the value stored in vp after type casting it to the (blank space)
s
proper data type pointer. the output is ‘g’. Similarly the output from second printf is ‘20’. The third
printf statement type casts it to print the string from the 4th value hence the output is ‘fy’. irl
rl
or
51. main ( ) l
{ Explanation:
static char *s[ ] = {“black”, “white”, “yellow”, “violet”}; Here a string (a pointer to char) is initialized with a value “girl”. The strlen function returns
ct
char **ptr[ ] = {s+3, s+2, s+1, s}, ***p; the length of the string, thus n has a value 4. The next statement assigns value at the nth location
(‘\0’) to the first location. Now the string becomes “\0irl” . Now the printf statement prints the string
p = ptr;
after each iteration it increments it starting position. Loop starts from 0 to 4. The first time x[0] = ‘\0’
ru
**++p; hence it prints nothing and pointer value is incremented. The second time it prints from x[1] i.e., “irl”
printf(“%s”,*--*++p + 3); and the third time it prints “rl” and the last time it prints “l” and the loop terminates.
} 53. int i,j;
Answer:
st
for(i=0;i<=10;i++)
ck {
Explanation: j+=5;
In
In this problem we have an array of char pointers pointing to start of 4 strings. Then we have assert(i<5);
ptr which is a pointer to a pointer of type char and a variable p which is a pointer to a pointer of type
char p hold the initial value of ptr, i.e., p = s+3. The next statement increment value in p by 1, thus }
now value of p = s+2. In the printf statement the expression is evaluated *++p causes gets value s+1 Answer:
then the pre decrement is executed and we get s+1 – 1 = s the indirection operator now gets the Runtime error: Abnormal program termination.
E
value from the array of s and adds 3 to the starting address. The string is printed starting from this
assert failed (i<5), <file name>,<line number>
position. Thus, the output is ‘ck’.
Explanation:
AT
52. main() Asserts are used during debugging to make sure that certain conditions are satisfied. If
assertion fails, the program will terminate reporting the same. After debugging use, #undef NDEBUG
{
and this will disable all the assertions from the source code. Assertion is a good debugging tool to
int i, n; make use of.
char *x = “girl”; 54. main()
G
n = strlen(x); {
*x = x[n];
int i=-1;
for(i=0; i<n; ++i)
+i;
printf(“i = %d, +i = %d \n”,i,+i); 59. main()
} {
Answer: main();
i = -1, +i = -1 }
Explanation: Answer:
Unary + is the only dummy operator in C. Where-ever it comes you can just ignore it Runtime error : Stack overflow.
just because it has no effect in the expressions (hence the name dummy operator). Explanation:
s
main function calls itself again and again. Each time the function is called its return
55. What are the files which are automatically opened when a C file is executed? address is stored in the call stack. Since there is no condition to terminate the function
or
Answer: call, the call stack overflows at runtime. So it terminates the program and results in an
error.
stdin, stdout, stderr (standard input,standard output,standard error).
60. main()
ct
56. What will be the position of the file marker?
{
a: fseek(ptr,0,SEEK_SET);
char *cptr,c;
b: fseek(ptr,0,SEEK_CUR);
ru
void *vptr,v;
c=10; v=0;
Answer:
cptr=&c; vptr=&v;
a: The SEEK_SET sets the file position marker to the starting of the file.
printf(“%c%v”,c,v);
st
b: The SEEK_CUR sets the file position marker to the current position of the file.
}
Answer:
57. main()
In
{ Compiler error (at line number 4): size of v is Unknown.
scanf(“ \”%[^\”]\“”,s); You can create a variable of type void * but not of type void, since void is an empty
type. In the second line you are creating variable vptr of type void * and v of type void
}
E hence an error.
How scanf will execute?
Answer:
61. main()
AT
First it checks for the leading white space and discards it.Then it matches with a
{
quotation mark and then it reads all character upto another quotation mark.
char *str1=“abcd”;
char str2[]=“abcd”;
58. What is the problem with the following code segment?
printf(“%d %d %d”,sizeof(str1),sizeof(str2),sizeof(“abcd”));
while ((fgets(receiving array,50,file_ptr)) != EOF);
G
}
Answer & Explanation:
Answer:
fgets returns a pointer. So the correct end of file check is checking for != NULL.
255
Explanation: else if(-1)
In first sizeof, str1 is a character pointer so it gives you the size of the pointer variable. puts(“TRUE”);
In second sizeof the name str2 indicates the name of the array whose size is 5 (including else
the ‘\0’ termination character). The third sizeof is similar to the second one.
puts(“FALSE”);
}
62. main()
Preprocessor doesn’t replace the values given inside the double quotes. The check by
{ if condition is boolean value false so it goes to else. In second if -1 is boolean value true
s
char not; hence “TRUE” is printed.
not=!2;
or
printf(“%d”,not); 64. main()
} {
Answer: int k=1;
ct
0 printf(“%d==1 is “”%s”,k,k==1?“TRUE“:”FALSE”);
Explanation: }
! is a logical operator. In C the value 0 is considered to be the boolean value FALSE Answer:
ru
and any non-zero value is considered to be the boolean value TRUE. Here 2 is a non-
zero value so TRUE. !TRUE is FALSE (0) so it prints 0. 1==1 is TRUE
Explanation:
63. #define FALSE -1 When two strings are placed together (or separated by white-space) they are
st
#define TRUE 1 concatenated (this is called as “stringization” operation). So the string is as if it is given
as “%d==1 is %s”. The conditional operator( ?: ) evaluates to “TRUE”.
#define NULL 0
In
main() {
if(NULL) 65. main()
puts(“NULL”); {
else if(FALSE) int y;
scanf(“%d”,&y); // input given is 2000
puts(“TRUE”);
E
else if( (y%4==0 && y%100 != 0) || y%100 == 0)
puts(“FALSE”); printf(“%d is a leap year”);
AT
} else
Answer: printf(“%d is not a leap year”);
TRUE }
Explanation:
Answer:
G
The input program to the compiler after processing by the preprocessor is,
2000 is a leap year.
main(){
Explanation:
if(0)
An ordinary program to check if leap year or not.
puts(“NULL”);
66. #define max 5 which is a valid declaration. i is assumed of type int. So printf prints 30. In the next
#define int arr1[max] block, i has value 20 and so printf prints 20. In the outermost block, i is declared as
extern, so no storage space is allocated for it. After compilation is over the linker
main()
resolves it to global variable i (since it is the only variable visible there). So it prints i’s
{ value as 10.
typedef char arr2[max];
arr1 list={0,1,2,3,4}; 68. main()
arr2 name=“name”; {
s
printf(“%d %s”,list[0],name); int *j;
} {
or
Answer: int i=10;
Compiler error (in the line arr1 list = {0,1,2,3,4}) j=&i;
Explanation: }
ct
arr2 is declared of type array of size 5 of characters. So it can be used to declare the printf(“%d”,*j);
variable name of the type arr2. But it is not the case of arr1. Hence an error.
}
Rule of Thumb:
Answer:
ru
#defines are used for textual replacement whereas typedefs are used for declaring
10
new types.
Explanation:
67. int i=10;
The variable i is a block level variable and the visibility is inside that block only. But the
st
main()
lifetime of i is lifetime of the function so it lives upto the exit of main function. Since the
{ i is still allocated space, *j prints the value stored in i since j points i.
extern int i;
In
{ 69. main()
int i=20; {
{ int i=-1;
const volatile unsigned i=30; -i;
E
printf(“%d”,i); printf(“i = %d, -i = %d \n”,i,-i);
} }
printf(“%d”,i);
AT
Answer:
} i = -1, -i = 1
printf(“%d”,i); Explanation:
} -i is executed and this execution doesn’t affect the value of i. In printf first you just
Answer: print the value of i. After that the value of the expression -i = -(-1) is printed.
G
30,20,10
Explanation: 70. #include<stdio.h>
‘{’ introduces new block and thus new scope. In the innermost block i is declared as, main()
const volatile unsigned.
{ Answer:
const int i=4; hello 5
float j; Explanation:
j = ++i; If you declare i as register compiler will treat it as ordinary integer and it will take
printf(“%d %f”, i,++j); integer value. i value may be stored either in register or in memory.
}
Answer: 73. main()
s
Compiler error {
Explanation: int i=5,j=6,z;
or
i is a constant. You cannot change the value of constant. printf(“%d”,i+++j);
}
71. #include<stdio.h> Answer:
ct
main() 11
{ Explanation:
int a[2][2][2] = { {10,2,3,4}, {5,6,7,8} }; The expression i+++j is treated as (i++ + j).
ru
int *p,*q;
p=&a[2][2][2]; 74. struct aaa{
*q=***a; struct aaa *prev;
st
printf(“%d..%d”,*p,*q); int i;
} struct aaa *next;
Answer: };
In
garbagevalue..1 main()
Explanation: {
p=&a[2][2][2] you declare only two 2D arrays but you are trying to access the third struct aaa abc,def,ghi,jkl;
2D(which you are not declared) it will print garbage values. *q=***a starting address int x=100;
E
of a is assigned integer pointer now q is pointing to starting address of a.if you print *q
abc.i=0;abc.prev=&jkl;
meAnswer:it will print first element of 3D array.
abc.next=&def;
AT
def.i=1;def.prev=&abc;def.next=&ghi;
72. #include<stdio.h>
main() ghi.i=2;ghi.prev=&def;
{ ghi.next=&jkl;
register i=5; jkl.i=3;jkl.prev=&ghi;jkl.next=&abc;
G
s
75. struct point 77. main()
{ {
or
int x; char *p;
int y; int *q;
}; long *r;
ct
struct point origin,*pp; p=q=r=0;
main() p++;
{ q++;
ru
pp=&origin; r++;
printf(“origin is(%d%d)\n”,(*pp).x,(*pp).y); printf(“%p...%p...%p”,p,q,r);
printf(“origin is (%d%d)\n”,pp->x,pp->y); }
st
} Answer:
Answer: 0001...0002...0004
origin is(0,0) Explanation:
In
origin is(0,0) ++ operator when applied to pointers increments address according to their
Explanation: corresponding data-types.
pp is a pointer to structure. We can access the elements of the structure either with
arrow mark or with indirection operator. 78. main()
E
Note: {
Since structure point is globally declared x & y are initialized as zeroes. char c=‘ ’,x,convert(z);
AT
getc(c);
76. main() if((c>=‘a’) && (c<=‘z’))
{ x=convert(c);
int i=_l_abc(10); printf(“%c”,x);
printf(“%d\n”,--i); }
G
} convert(z)
int _l_abc(int i) {
{ return z-32;
} Explanation:
Answer: ptr pointer is pointing to out of the array range of one_d.
Compiler error.
Explanation: 81. # include<stdio.h>
Declaration of convert and format of getc() are wrong. aaa() {
printf(“hi”);
79. main(int argc, char **argv) }
s
{ bbb(){
printf(“enter the character”); printf(“hello”);
or
getchar(); }
sum(argv[1],argv[2]); ccc(){
} printf(“bye”);
ct
sum(num1,num2) }
int num1,num2; main()
{ {
ru
return num1+num2; int (*ptr[3])();
} ptr[0]=aaa;
ptr[1]=bbb;
st
Answer: ptr[2]=ccc;
Compiler error. ptr[2]();
Explanation: }
In
argv[1] & argv[2] are strings. They are passed to the function sum without converting Answer:
it to integer values. bye
Explanation:
80. # include <stdio.h>
ptr is array of pointers to functions of return type int.ptr[0] is assigned to address of the
E
int one_d[]={1,2,3}; function aaa. Similarly ptr[1] and ptr[2] for bbb and ccc respectively. ptr[2]() is in
main() effect of writing ccc(), since ptr[2] points to ccc.
AT
{
int *ptr;
82. #include<stdio.h>
ptr=one_d;
main()
ptr+=3;
{
printf(“%d”,*ptr);
G
FILE *ptr;
}
char i;
Answer:
ptr=fopen(“zzz.c”,“r”);
garbage value
while((i=fgetch(ptr))!=EOF) Explanation:
printf(“%c”,i); Normally the return value from the function is through the information from the
} accumulator. Here _AH is the pseudo global variable denoting the accumulator. Hence,
the value of the accumulator is set 1000 so the function returns value 1000.
Answer:
contents of zzz.c followed by an infinite loop.
85. int i;
Explanation:
main(){
The condition is checked against EOF, it should be checked against NULL.
s
int t;
for ( t=4;scanf(“%d”,&i)-t;printf(“%d\n”,i))
83. main()
or
printf(“%d--”,t--);
{
}
int i =0;j=0;
// If the inputs are 0,1,2,3 find the o/p
if(i && j++)
ct
Answer:
printf(“%d..%d”,i++,j);
4--0
printf(“%d..%d,i,j);
3--1
}
ru
2--2
Answer:
Explanation:
0..0
Let us assume some x= scanf(“%d”,&i)-t the values during execution will be,
Explanation:
st
t i x
The value of i is 0. Since this information is enough to determine the truth value of the
4 0 -4
boolean expression. So the statement following the if statement is not executed. The
values of i and j remain unchanged and get printed. 3 1 -2
In
2 2 0
84. main()
{ 86. main(){
int a= 0;int b = 20;char x =1;char y =10;
int i;
E
i = abc(); if(a,b,x,y)
printf(“%d”,i); printf(“hello”);
AT
} }
abc() Answer:
{ hello
} The comma operator has associativity from left to right. Only the rightmost value is
returned and the other values are evaluated and ignored. Thus the value of last variable
Answer:
y is returned to check in if. Since it is a non zero value if becomes true so, “hello” will
1000 be printed.
87. main(){ Answer:
unsigned int i; i. ANSI C notation
for(i=1;i>-2;i--) ii. Kernighan & Ritche notation.
printf(“c aptitude”);
} 90. main()
Explanation: {
i is an unsigned integer. It is compared with a signed value. Since the both types char *p;
s
doesn’t match, signed is promoted to unsigned value. The unsigned equivalent of -2 is p=“%d\n”;
a huge value so condition becomes false and control comes out of the loop.
p++;
or
p++;
88. In the following pgm add a stmt in the function fun such that the address of ‘a’ gets stored
printf(p-2,300);
in ‘j’.
}
main(){
ct
Answer:
int * j;
300
void fun(int **);
Explanation:
ru
fun(&j);
The pointer points to % since it is incremented twice and again decremented by 2, it
}
points to ‘%d\n’ and 300 is printed.
void fun(int **k) {
int a =0;
st
91. main(){
/* add a stmt here*/
char a[100];
}
a[0]=‘a’;a[1]=‘b’;a[2]=‘c’;a[4]=‘d’;
In
Answer:
abc(a);
*k = &a
}
Explanation:
abc(char a[]){
The argument of the function is a pointer to a pointer.
a++;
E
printf(“%c”,*a);
89. What are the following notations of defining functions known as?
a++;
i. int abc(int a,float b)
AT
printf(“%c”,*a);
{
}
/* some code */
} Explanation:
ii. int abc(a,b) The base address is modified only in function and as a result a points to ‘b’ then after
incrementing to ‘c’ so bc will be printed.
int a; float b;
G
{
/* some code*/ 92. func(a,b)
} int a,b;
{ Explanation:
return( a= (a==b) ); The variable “I” is declared as static, hence memory for I will be allocated for only
} once, as it encounters the statement. The function main() will be called recursively
unless I becomes equal to 0, and since main() is recursively called, so the value of
main()
static I ie., 0 will be printed every time the control is returned.
{
int process(),func();
94. void main()
printf(“The value of process is %d !\n ”,process(func,3,6));
{
s
}
int k=ret(sizeof(float));
process(pf,val1,val2)
or
printf(“\n here value is %d”,++k);
int (*pf) ();
}
int val1,val2;
int ret(int ret)
{
{
ct
return((*pf) (val1,val2));
ret += 2.5;
}
return(ret);
ru
}
Answer:
Answer:
The value of process is 0 !
Here value is 7
Explanation:
Explanation:
st
The function ‘process’ has 3 parameters - 1, a pointer to another function 2 and 3,
The int ret(int ret), ie., the function name and the argument name can be the same.
integers. When this function is invoked from main, the following substitutions for formal
parameters take place: func for pf, 3 for val1 and 6 for val2. This function returns the Firstly, the function ret() is called in which the sizeof(float) i.e., 4 is passed, after the
In
result of the operation performed by the function ‘func’. The function func has two first expression the value in ret will be 6, as ret is integer hence the value stored in ret
integer parameters. The formal parameters are substituted as 3 for a and 6 for b. since will have implicit type conversion from float to int. The ret is returned in main() it is
3 is not equal to 6, a==b returns 0. Therefore the function returns 0 which in turn is printed after and preincrement.
returned by the function ‘process’.
95. void main()
E
93. void main() {
{ char a[]=“12345\0”;
AT
static int i=5; int i=strlen(a);
if(--i){ printf(“here in 3 %d\n”,++i);
main(); }
printf(“%d ”,i); Answer:
} here in 3 6
G
} Explanation:
Answer: The char array ‘a’ will hold the initialized string, whose length will be counted from 0 till
0000 the null character. Hence the ‘I’ will hold the value equal to 5, after the pre-increment
in the printf statement, the 6 will be printed.
96. void main() Explanation:
{ Void pointer is a generic pointer type. No pointer arithmetic can be done on it. Void
unsigned giveit=-1; pointers are normally used for:
int gotit; 1. Passing generic pointers to functions and returning such pointers.
printf(“%u ”,++giveit); 2. As a intermediate pointer type.
printf(“%u \n”,gotit=--giveit); 3. Used when the exact pointer type will be known at a later point of time.
} 99. void main()
s
Answer: {
0 65535 int i=i++,j=j++,k=k++;
or
Explanation: printf(“%d%d%d”,i,j,k);
give it value is incremented. In printf, the value of gotit is the decrement of give it. }
97. void main() Answer:
ct
{ Garbage values.
int i; Explanation:
char a[]=“\0”; An identifier is available to use in program code from the point of its declaration.
ru
if(printf(“%s\n”,a)) So expressions such as i = i++ are valid statements. The i, j and k are automatic
variables and so they contain some garbage value. Garbage in is garbage out (GIGO).
printf(“Ok here \n”);
100. void main()
else
st
{
printf(“Forget it\n”);
static int i=i++, j=j++, k=k++;
}
printf(“i = %d j = %d k = %d”, i, j, k);
Answer:
In
}
Ok here
Explanation: Answer:
printf will return how many characters does it print. Hence printing a null character i=1j=1k=1
returns 1 which makes the if statement true, thus “Ok here” is printed. Explanation:
E
Since static variables are initialized to zero by default.
98. void main() 101. void main()
{ {
AT
void *v; while(1){
int integer=2; if(printf(“%d”,printf(“%d”)))
int *i=&integer; break;
v=i;
else
printf(“%d”,(int*)*v);
G
continue;
}
}
Answer:
}
Compiler Error. We cannot apply indirection on type void*.
Answer: 104. main()
Garbage values {
Explanation: int a[10];
The inner printf executes first to print some garbage value. The printf returns No. of printf(“%d”,*a+1-*a+3);
characters printed and this value also cannot be predicted. Still the outer printf prints }
something and so returns a non-zero value. So it encounters the break statement and
Answer:
comes out of the while statement.
4
s
Explanation:
102. main()
*a and -*a cancels out. The result is as simple as 1 + 3 = 4 !
or
{
unsigned int i=10;
105. #define prod(a,b) a*b
while(i-->=0)
main()
printf(“%u ”,i);
ct
{
int x=3,y=4;
}
printf(“%d”,prod(x+2,y-1));
ru
Answer:
}
10 9 8 7 6 5 4 3 2 1 0 65535 65534…..
Answer:
Explanation:
10
Since i is an unsigned integer it can never become negative. So the expression i-- >=0
st
will always be true, leading to an infinite loop. Explanation:
The macro expands and evaluates to as:
103. #include<conio.h> x+2*y-1 => x+(2*y)-1 => 10
In
main()
{ 106. main()
int x,y=2,z,a; {
unsigned int i=65000;
if(x=y%2) z=2;
E
a=2; while(i++!=0);
printf(“%d %d”,z,x); printf("%d",i);
AT
} }
Answer: Answer:
Garbage-value 0 1
Explanation: Explanation:
Note the semicolon after the while statement. When the value of i becomes 0 it comes
G
The value of y%2 is 0. This value is assigned to x. The condition reduces to if (x) or in
other words if(0) and so z goes uninitialized. out of while loop. Due to post-increment on i the value of i while printing is 1.
Thumb Rule: Check all control paths to write bug free code. 107. main()
{
int i=0; }
while(+(+i--)!=0) void pascal f(integer :i,integer:j,integer :k)
i-=i++; {
printf(“%d”,i); write(i,j,k);
} }
Answer: Answer:
-1 Compiler error: unknown type integer
s
Explanation: Compiler error: undeclared function write
Unary + is the only dummy operator in C. So it has no effect on the expression and Explanation:
or
now the while loop is, while(i--!=0) which is false and so breaks out of while loop. The Pascal keyword doesn’t mean that pascal code can be used. It means that the function
value –1 is printed due to the post-decrement operator. follows Pascal argument passing mechanism in calling the functions.
ct
108. main() 110. void pascal f(int i,int j,int k)
{ {
float f=5,g=10; printf(“%d %d %d”,i, j, k);
ru
enum{i=10,j=20,k=50}; }
printf(“%d\n”,++k); void cdecl f(int i,int j,int k)
printf(“%f\n”,f<<2); {
st
printf(“%lf\n”,f%g); printf(“%d %d %d”,i, j, k);
printf(“%lf\n”,fmod(f,g)); }
} main()
In
Answer: {
Line no 5: Error: Lvalue required int i=10;
Line no 6: Cannot apply leftshift to float f(i++,i++,i++);
Line no 7: Cannot apply mod to float printf(“ %d\n”,i);
E
Explanation:
i=10;
Enumeration constants cannot be modified, so you cannot apply ++.
f(i++,i++,i++);
Bit-wise operators and % operators cannot be applied on float values.
AT
printf(“ %d”,i);
fmod() is to find the modulus values for floats as % operator is for ints.
}
Answer:
109. main()
{ 10 11 12 13
int i=10; 12 11 10 13
G
s
}
You can write programs that have implementation dependent behavior. But don’t write
Answer: programs that depend on such behavior.
or
-128
Explanation: 114. Is the following statement a declaration/definition. Find what does it mean?
Notice the semicolon at the end of the for loop. The initial value of the i is set to 0. The int (*x)[10];
ct
inner loop executes to increment the value from 0 to 127 (the positive range of char)
Answer:
and then it rotates to the negative value of -128. The condition in the for loop fails and
so comes out of the for loop. It prints the current value of i that is -128. Definition.
x is a pointer to array of(size 10) integers.
ru
112. main() Apply clock-wise rule to find the meaning of this definition.
{
unsigned char i=0; 115. What is the output for the program given below?
st
for(;i>=0;i++) ; typedef enum errorType{warning, error, exception,}error;
printf(“%d\n”,i); main()
In
} {
Answer: error g1;
infinite loop g1=1;
Explanation: printf(“%d”,g1);
E }
The difference between the previous question and this one is that the char is declared
to be unsigned. So the i++ can never yield negative value and i>=0 never becomes Answer:
false so that it can come out of the for loop. Compiler error: Multiple declaration for error.
AT
Explanation:
113. main() The name error is used in the two meanings. One means that it is a enumerator constant
{ with value 1. The another use is that it is a type name (due to typedef) for enum
char i=0; errorType. Given a situation the compiler cannot distinguish the meaning of error to
know in what sense the error is used:
for(;i>=0;i++) ;
G
error g1;
printf(“%d\n”,i);
g1=error;
// which error it refers in each case?
}
When the compiler can distinguish between usages then it will not issue error (in pure 117. #ifdef something
technical terms, names can only be overloaded in different namespaces). int some=0;
Note: The extra comma in the declaration, enum errorType{warning, error, exception,} #endif
is not an error. An extra comma is valid and is provided just for programmer’s main()
convenience.
{
int thing = 0;
116. typedef struct error{int warning, error, exception;}error;
printf(“%d %d\n”, some ,thing);
s
main()
{ }
or
error g1; Answer:
g1.error =1; Compiler error : undefined symbol some
printf(“%d”,g1.error); Explanation:
ct
} This is a very simple example for conditional compilation. The name something is not
Answer: already known to the compiler making the declaration
1 int some = 0;
ru
Explanation: effectively removed from the source code.
The three usages of name errors can be distinguishable by the compiler at any instance,
so valid (they are in different namespaces). 118. #if something == 0
Typedef struct error{int warning, error, exception;}error;
st
int some=0;
This error can be used only by preceding the error by struct kayword as in: #endif
struct error someError; main()
In
typedef struct error{int warning, error, exception;}error; {
This can be used only after . (dot) or -> (arrow) operator preceded by the variable int thing = 0;
name as in :
printf(“%d %d\n”, some ,thing);
g1.error =1;
}
E
printf(“%d”,g1.error);
Answer:
typedef struct error{int warning, error, exception;}error;
00
AT
This can be used to define variables without using the preceding struct keyword as in:
Explanation:
error g1;
This code is to show that preprocessor expressions are not the same as the ordinary
Since the compiler can perfectly distinguish between these three usages, it is perfectly expressions. If a name is not known the preprocessor treats it to be equal to zero.
legal and valid.
119. What is the output for the following program?
Note:
G
main()
This code is given here to just explain the concept behind. In real programming don’t
use such overloading of names. It reduces the readability of the code. Possible doesn’t {
mean that we should use it! int arr2D[3][3];
printf(“%d\n”, ((arr2D==* arr2D)&&(* arr2D == arr2D[0])) ); 121. int swap(int *a,int *b)
} {
Answer: *a=*a+*b;*b=*a-*b;*a=*a-*b;
1 }
Explanation: main()
This is due to the close relation between the arrays and pointers. N dimensional arrays {
are made up of (N-1) dimensional arrays. arr2D is made up of a 3 single arrays that int x=10,y=20;
s
contains 3 integers each. swap(&x,&y);
arr2D printf(“x= %d y = %d\n”,x,y);
or
}
Answer:
x = 20 y = 10
ct
arr2D[1] Explanation:
arr2D[2] This is one way of swapping two values. Simple checking will help understand this.
arr2D[3]
ru
The name arr2D refers to the beginning of all the 3 arrays. *arr2D refers to the start of 122. main()
the first 1D array (of 3 integers) that is the same address as arr2D. So the expression {
(arr2D == *arr2D) is true (1).
char *p = “ayqm”;
Similarly, *arr2D is nothing but *(arr2D + 0), adding a zero doesn’t change the value/
st
printf(“%c”,++*(p++));
meaning. Again arr2D[0] is the another way of telling *(arr2D + 0). So the expression
(*(arr2D + 0) == arr2D[0]) is true (1). }
Since both parts of the expression evaluates to true the result is true(1) and the same is Answer:
In
printed. b
Explanation:
120. void main() Address of p is incremented and the value of p is incremented after that.
{ 123. main()
E
if(~0 == (unsigned int)-1) {
printf(“You can answer this if you know how values are represented in memory”); int i=5;
printf(“%d”,++i++);
AT
}
}
Answer:
Answer: Compiler error: Lvalue required in function main
You can answer this if you know how values are represented in memory. Explanation:
Explanation: ++i yields an rvalue. For postfix ++ to operate an lvalue is required.
G
~ (tilde operator or bit-wise negation operator) operates on 0 to produce all ones to fill
the space for an integer. –1 is represented in unsigned value as all 1’s and so both are 124. main()
equal. {
char *p = “ayqm”;
char c; int i=5;
c = ++*p++; printf(“%d”,i=++i ==6);
printf(“%c”,c); }
}
Answer: Answer:
b 1
Explanation: Explanation:
s
There is no difference between the expression ++*(p++) and ++*p++. Parenthesis just The expression can be treated as i = (++i==6), because == is of higher precedence
works as a visual clue for the reader to see which expression is first evaluated. than = operator. In the inner expression, ++i is equal to 6 yielding true(1). Hence the
or
result.
ct
{
iny ccc(){printf(“bye”);}
char p[ ]=“%d\n”;
p[1] = ‘c’;
ru
main() printf(p,65);
{ }
int ( * ptr[3]) (); Answer:
st
ptr[0] = aaa; A
ptr[1] = bbb; Explanation:
ptr[2] =ccc; Due to the assignment p[1] = ‘c’ the string becomes, “%c\n”. Since this string becomes
In
ptr[2](); the format string for printf and ASCII value of 65 is ‘A’, the same gets printed.
}
128. void ( * abc( int, void ( *def) () ) ) ();
Answer:
bye
E
Answer:
Explanation:
abc is a ptr to a function which takes 2 parameters .(a). an integer variable.(b). a ptrto
int (* ptr[3])() says that ptr is an array of pointers to functions that takes no arguments a funtion which returns void. the return type of the function is void.
AT
and returns the type int. By the assignment ptr[0] = aaa; it means that the first function
Explanation:
pointer in the array is initialized with the address of the function aaa. Similarly, the other
Apply the clock-wise rule to find the result.
two array elements also get initialized with the addresses of the functions bbb and ccc.
Since ptr[2] contains the address of the function ccc, the call to the function ptr[2]() is
same as calling ccc(). So it results in printing “bye”. 129. main()
G
{
126. main() while (strcmp(“some”,“some\0”))
{ printf(“Strings are not equal\n”);
}
Answer: 132. void main()
No output {
Explanation: int *mptr, *cptr;
Ending the string constant with \0 explicitly makes no difference. So “some” and mptr = (int*)malloc(sizeof(int));
“some\0” are equivalent. So, strcmp returns 0 (false) hence breaking out of the while printf(“%d”,*mptr);
loop.
int *cptr = (int*)calloc(sizeof(int),1);
printf(“%d”,*cptr);
s
130. main()
}
{
Answer:
or
char str1[] = {‘s’,‘o’,‘m’,‘e’};
garbage-value 0
char str2[] = {‘s’,‘o’,‘m’,‘e’,‘\0’};
Explanation:
while (strcmp(str1,str2))
The memory space allocated by malloc is uninitialized, whereas calloc returns the
ct
printf(“Strings are not equal\n”); allocated memory space initialized to zeros.
}
Answer: 133. void main()
ru
“Strings are not equal” {
“Strings are not equal” static int i;
…. while(i<=10)
st
Explanation: (i>2)?i++:i--;
If a string constant is initialized explicitly with characters, ‘\0’ is not appended printf(“%d”, i);
automatically to the string. Since str1 doesn’t have null termination, it treats whatever
}
In
the values that are in the following positions as part of the string until it randomly
reaches a ‘\0’. So str1 and str2 are not the same, hence the result. Answer:
32767
131. main() Explanation:
{ Since i is static it is initialized to 0. Inside the while loop the conditional operator evaluates
E
to false, executing i--. This continues till the integer value rotates to positive value
int i = 3;
(32767). The while condition becomes false and hence, comes out of the while loop,
for (;i++=0;) printf(“%d”,i); printing the i value.
AT
}
134. main()
Answer: {
Compiler Error: Lvalue required. int i=10,j=20;
Explanation:
G
j = i, j?(i,j)?i:j:j;
As we know that increment operators return rvalues and hence it cannot appear on printf(“%d %d”,i,j);
the left hand side of an assignment operation.
}
Answer:
10 10 Answer:
Explanation: 1 10
The Ternary operator ( ? : ) is equivalent for if-then-else statement. So the question Explanation:
can be written as: The expression can be written as i=(i&=(j&&10)); The inner expression (j&&10)
if(i,j) evaluates to 1 because j==10. i is 5. i = 5&1 is 1. Hence the result.
{ 137. main()
s
if(i,j) {
j = i; int i=4,j=7;
or
else j = j || i++ && printf(“YOU CAN”);
j = j; printf(“%d %d”, i, j);
} }
ct
else
j = j; Answer:
135. 1. const char *a; 41
ru
2. char* const a; Explanation:
3. char const *a; The boolean expression needs to be evaluated only till the truth value of the
-Differentiate the above declarations. expression is not known. j is not equal to zero itself means that the expression’s truth
value is 1. Because it is followed by || and true || (anything) => true where (anything)
st
will not be evaluated. So the remaining expression is not evaluated and so the value
Answer: of i remains the same.
1. ‘const’ applies to char * rather than ‘a’ ( pointer to a constant char ) Similarly when && operator is involved in an expression, when any of the operands
In
*a=‘F’ : illegal become false, the whole expression’s truth value becomes false and hence the remaining
a=“Hi” : legal expression will not be evaluated. false && (anything) => false where (anything)
will not be evaluated.
2. ‘const’ applies to ‘a’ rather than to the value of a (constant pointer to char )
E
*a=‘F’ : legal 138. main()
{
a=“Hi” : illegal
register int a=2;
AT
3. Same as 1.
printf(“Address of a = %d”,&a);
136. main()
printf(“Value of a = %d”,a);
{
}
int i=5,j=10;
G
i=i&=j&&10;
Answer:
printf(“%d %d”,i,j); Compiler Error: ‘&’ on register variable
} Rule to Remember:
& (address of ) operator cannot be applied on register variables.
139. main() printf(“\n%d %d %d”,a,*f1,*f2);
{ }
float i=1.5; Answer:
switch(i) 16 16 16
{ Explanation:
case 1: printf(“1”); f1 and f2 both refer to the same memory location a. So changes through f1 and f2
case 2: printf(“2”); ultimately affects only the value of a.
s
default : printf(“0”);
} 142. main()
or
} {
Answer: char *p=“GOOD”;
Compiler Error: switch expression not integral char a[ ]=“GOOD”;
ct
Explanation: printf(“\n sizeof(p) = %d, sizeof(*p) = %d, strlen(p) = %d”, sizeof(p),
Switch statements can be applied only to integral types. sizeof(*p), strlen(p));
printf(“\n sizeof(a) = %d, strlen(a) = %d”, sizeof(a), strlen(a));
ru
140. main() }
{ Answer:
extern i; sizeof(p) = 2, sizeof(*p) = 1, strlen(p) = 4
st
printf(“%d\n”,i); sizeof(a) = 5, strlen(a) = 4
{ Explanation:
int i=20; sizeof(p) => sizeof(char*) => 2
In
printf(“%d\n”,i); sizeof(*p) => sizeof(char) => 1
} Similarly,
} sizeof(a) => size of the character array => 5
Answer: When sizeof operator is applied to an array it returns the sizeof the array and it is
E
not the same as the sizeof the pointer variable. Here the sizeof(a) where a is the
Linker Error : Unresolved external symbol i
character array and the size of the array is 5 because the space necessary for the
Explanation: terminating NULL character should also be taken into account.
AT
The identifier i is available in the inner block and so using extern has no use in resolving
it.
143. #define DIM( array, type) sizeof(array)/sizeof(type)
main()
141. main()
{
{
G
int arr[10];
int a=2,*f1,*f2;
printf(“The dimension of the array is %d”, DIM(arr, int));
f1=f2=&a;
}
*f2+=*f2+=a+=2.5;
Answer: Answer:
10 1 1 1 1
Explanation: 2 4 2 4
The size of integer array of 10 elements is 10 * sizeof(int). The macro expands to 3 7 3 7
sizeof(arr)/sizeof(int) => 10 * sizeof(int) / sizeof(int) => 10. 4 2 4 2
5 5 5 5
144. int DIM(int array[]) 6 8 6 8
s
{ 7 3 7 3
return sizeof(array)/sizeof(int ); 8 6 8 6
or
} 9 9 9 9
main() Explanation:
{ *(*(p+i)+j) is equivalent to p[i][j].
ct
int arr[10];
printf(“The dimension of the array is %d”, DIM(arr)); 146. main()
} {
ru
Answer: void swap();
1 int x=10,y=8;
Explanation: swap(&x,&y);
st
Arrays cannot be passed to functions as arguments and only the pointers can be passed. printf(“x=%d y=%d”,x,y);
So the argument is equivalent to int * array (this is one of the very few places where []
}
and * usage are equivalent). The return statement becomes, sizeof(int *)/ sizeof(int)
void swap(int *a, int *b)
In
that happens to be equal in this case.
{
145. main() *a ^= *b, *b ^= *a, *a ^= *b;
{ }
Answer:
static int a[3][3]={1,2,3,4,5,6,7,8,9};
E
int i,j; x=10 y=8
static *p[]={a,a+1,a+2}; Explanation:
AT
for(i=0;i<3;i++) Using ^ like this is a way to swap two variables without using a temporary variable and
that too in a single statement.
{
for(j=0;j<3;j++) Inside main(), void swap(); means that swap is a function that may take any number of
arguments (not no arguments) and returns nothing. So this doesn’t issue a compiler
printf(“%d\t%d\t%d\t%d\n”,*(*(p+i)+j),
error by the call swap(&x,&y); that has two arguments.
G
*(*(j+p)+i),*(*(i+p)+j),*(*(p+j)+i));
This convention is historically due to pre-ANSI style (referred to as Kernighan and
}
Ritchie style) style of function declaration. In that style, the swap function will be
}
defined as follows,
void swap() 149. main()
int *a, int *b {
{ int i=300;
*a ^= *b, *b ^= *a, *a ^= *b; char *ptr = &i;
} *++ptr=2;
where the arguments follow the (). So naturally the declaration for swap will look like, printf(“%d”,i);
void swap() which means the swap can take any number of arguments. }
s
Answer:
147. main() 556
or
{ Explanation:
int i = 257; The integer value 300 in binary notation is: 00000001 00101100. It is stored in memory
int *iPtr = &i; (small-endian) as: 00101100 00000001. Result of the expression *++ptr = 2 makes the
ct
printf(“%d %d”, *((char*)iPtr), *((char*)iPtr+1) ); memory representation as: 00101100 00000010. So the integer corresponding to it is
00000010 00101100 => 556.
}
Answer:
ru
150. #include <stdio.h>
11
main()
Explanation:
{
The integer value 257 is stored in the memory as, 00000001 00000001, so the individual
char * str = “hello”;
st
bytes are taken by casting it to char * and get printed.
char * ptr = str;
148. main() char least = 127;
In
{ while (*ptr++)
int i = 258; least = (*ptr<least ) ?*ptr :least;
int *iPtr = &i; printf(“%d”,least);
printf(“%d %d”, *((char*)iPtr), *((char*)iPtr+1) ); }
E
} Answer:
0
Answer: Explanation:
AT
21 After ‘ptr’ reaches the end of the string the value pointed by ‘str’ is ‘\0’. So the value of
‘str’ is less than that of ‘least’. So the value of ‘least’ finally is 0.
Explanation:
The integer value 257 can be represented in binary as, 00000001 00000001. Remember
that the INTEL machines are ‘small-endian’ machines. Small-endian means that the 151. Declare an array of N pointers to functions returning pointers to functions returning pointers
to characters?
G
lower order bytes are stored in the higher memory addresses and the higher order
bytes are stored in lower addresses. The integer value 258 is stored in memory as: Answer:
00000001 00000010. (char*(*)( )) (*ptr[N])( );
152. main() Answer:
{ Compiler Error: Undefined structure date
struct student Explanation:
{ Only declaration of struct date is available inside the structure definition of ‘student’
char name[30]; but to have a variable of type struct date the definition of the structure is required.
struct date dob;
}stud; 154. There were 10 records stored in “somefile.dat” but the following program printed 11 names.
s
What went wrong?
struct date
void main()
{
or
{
int day,month,year;
struct student
};
{
scanf(“%s%d%d%d”, stud.rollno, &student.dob.day, &student.dob.month,
ct
char name[30], rollno[6];
&student.dob.year);
}stud;
}
FILE *fp = fopen(“somefile.dat”,“r”);
Answer:
ru
while(!feof(fp))
Compiler Error: Undefined structure date
{
Explanation:
fread(&stud, sizeof(stud), 1 , fp);
Inside the struct definition of ‘student’ the member of type struct date is given. The
st
compiler doesn’t have the definition of date structure (forward reference is not allowed puts(stud.name);
in C in this case) so it issues an error. }
}
In
153. main() Explanation:
{ fread reads 10 records and prints the names successfully. It will return EOF only when
struct date; fread tries to read another record and fails reading EOF (and returning EOF). So it
prints the last record again. After this only the condition feof(fp) becomes false, hence
struct student
comes out of the while loop.
E
{
char name[30];
155. Is there any difference between the two declarations?
struct date dob;
AT
1. int foo(int *arr[]) and
}stud;
2. int foo(int *arr[2])
struct date
Answer:
{
No
int day,month,year;
Explanation:
G
};
Functions can only pass pointers and not arrays. The numbers that are allowed inside
scanf(“%s%d%d%d”, stud.rollno, &student.dob.day, &student.dob.month, the [] is just for more readability. So there is no difference between the two declarations.
&student.dob.year);
}
156. What is the subtle error in the following code segment? 159. void main()
void fun(int n, int arr[]) {
{ int *i = 0x400; // i points to the address 400
int *p=0; *i = 0; // set the value of memory location pointed by i;
int i=0; }
while(i++<n)
p = &arr[i]; Answer:
s
*p = 0; Undefined behavior
} Explanation:
or
Answer & Explanation: The second statement results in undefined behavior because it points to some location
If the body of the loop never executes p is assigned no address. So p remains NULL whose value may not be available for modification. This type of pointer in which the
where *p =0 may result in problem (may rise to runtime error “NULL pointer assignment” non-availability of the implementation of the referenced location is known as ‘incomplete
type’.
ct
and terminate the program).
157. What is wrong with the following code? 160. #define assert(cond) if(!(cond)) \
ru
int *foo() (fprintf(stderr, “assertion failed: %s, file %s, line %d \n”,#cond,\
{ __FILE__,__LINE__), abort())
int *s = malloc(sizeof(int)100);
void main()
st
assert(s != NULL);
return s; {
} int i = 10;
In
if(i==0)
Answer & Explanation: assert(i < 100);
assert macro should be used for debugging and finding out bugs. The check s != NULL is else
for error/exception handling and for that assert shouldn’t be used. A plain if and the printf(“This statement becomes else for if in assert macro”);
corresponding remedy statement has to be given.
E
}
158. What is the hidden bug with the following statement? Answer:
AT
assert(val++ != 0); No output
Answer & Explanation: Explanation:
assert macro is used for debugging and removed in release version. In assert, the The else part in which the printf is there becomes the else for if in the assert macro.
experssion involves side-effects. So the behavior of the code becomes different in Hence nothing is printed.
case of debug version and the release version thus leading to a subtle bug.
G
s
} No
Explanation:
or
161. Is the following code legal? The typename aType is not known at the point of declaring the structure (forward
struct a references are not made for typedefs).
{
ct
int x; 164. Is the following code legal?
struct a b; typedef struct a aType;
} struct a
ru
Answer: {
No int x;
Explanation: aType *b;
st
It is not legal for a structure to contain a member that is of the same type as in this };
case. Because this will cause the structure declaration to be recursive without end. Answer:
Yes
In
162. Is the following code legal? Explanation:
The typename aType is known at the point of declaring the structure, because it is
struct a
already typedefined.
{ 165. Is the following code legal?
E
int x; void main()
struct a *b; {
typedef struct a aType;
AT
}
Answer: aType someVariable;
struct a
Yes.
{
Explanation:
int x;
G
*b is a pointer to type struct a and so is legal. The compiler knows, the size of the
aType *b;
pointer to a structure even before the size of the structure is determined(as you know
};
the pointer to any type is of same size). This type of structures is known as ‘self-
}
referencing’ structure.
Answer: Answer & Explanation:
No Prefer the first one. If the str contains any format characters like %d then it will result
Explanation: in a subtle bug.
When the declaration, 169. void main()
typedef struct a aType; {
is encountered body of struct a is not known. This is known as ‘incomplete types’. int i=10, j=2;
int *ip= &i, *jp = &j;
s
166. void main() int k = *ip/*jp;
{ printf(“%d”,k);
or
printf(“sizeof (void *) = %d \n”, sizeof( void *)); }
printf(“sizeof (int *) = %d \n”, sizeof(int *));
printf(“sizeof (double *) = %d \n”, sizeof(double *)); Answer:
ct
printf(“sizeof(struct unknown *) = %d \n”, sizeof(struct unknown *)); Compiler Error: “Unexpected end of file in comment started in line 5”.
} Explanation:
Answer: The programmer intended to divide two integers, but by the “maximum munch” rule,
ru
sizeof (void *) = 2 the compiler treats the operator sequence / and * as /* which happens to be the starting
of comment. To force what is intended by the programmer,
sizeof (int *) =2
int k = *ip/ *jp;
sizeof (double *) = 2
st
// give space explicity separating / and *
sizeof(struct unknown *) = 2
//or
Explanation:
int k = *ip/(*jp);
The pointer to any type is of same size.
In
// put braces to force the intention will solve the problem.
The second one is better because gets(inputString) doesn’t know the size of the string }
passed and so, if a very big input (here, more than 100 chars) the charactes will be
written past the input string. When fgets is used with stdin performs the same operation
Answer:
as gets but is safe.
Implementaion dependent
168. Which version do you prefer of the following two?
G
Explanation:
1) printf(“%s”,str); // or the more curt one
The char type may be signed or unsigned by default. If it is signed then ch++ is executed
2) printf(str); after ch reaches 127 and rotates back to -128. Thus ch is always smaller than 127.
171. Is this code legal? k++;
int *ptr; printf(“\n %u %u ”,j,k);
ptr = (int *) 0x400; }
Answer: Answer:
Yes Compiler error: Cannot increment a void pointer
Explanation: Explanation:
The pointer ptr will point at the integer in the memory location 0x400. Void pointers are generic pointers and they can be used only when the type is not
s
172. main() known and as an intermediate address storage type. No pointer arithmetic can be done
on it and you cannot apply indirection operator (*) on void pointers.
{
or
char a[4]=“HELLO”;
175. main()
printf(“%s”,a);
{
}
ct
extern int i;
Answer:
{ int i=20;
Compiler error: Too many initializers
{
Explanation:
ru
const volatile unsigned i=30; printf(“%d”,i);
The array a is of size 4 but the string constant requires 6 bytes to get stored.
}
printf(“%d”,i);
173. main()
st
}
{
printf(“%d”,i);
char a[4]=“HELL”;
}
printf(“%s”,a);
In
int i;
}
Answer:
176. printf can be implemented by using __________ list.
HELL%@!~@!@???@~~!
Answer:
Explanation:
E
Variable length argument lists
The character array has the memory just enough to hold the string “HELL” and doesnt
have enough space to store the terminating null character. So it prints the HELL correctly 177. char *someFun()
and continues to print garbage values till it accidentally comes across a NULL character. {
AT
void *k; {
j=k=&a; puts(someFun());
j++; }
Answer: char *k1=“hitechskill.com”;
string constant char *k2;
Explanation: k2=(char*)malloc(20);
The program suffers no problem and gives the output correctly because the character memset (k2, 0, 20);
constants are stored in code/data area and not allocated in stack, so this doesn’t lead to while(*k2++ = *k1++);
dangling pointers.
printf(“%s\n”,k2);
s
178. char *someFun1()
}
{
or
char temp[ ] = “string";
Answer: empty string.
return temp;
}
180. What will be printed as the result of the operation below?
ct
char *someFun2()
main()
{
{
char temp[ ] = {‘s’, ‘t’,‘r’,‘i’,‘n’,‘g’};
int a=20,b=35;
ru
return temp;
a=b++ + a++;
}
b= ++b + ++a;
int main()
printf(“%d%d\n”,a,b);
st
{
puts(someFun1());
}
puts(someFun2());
Answer: 5794
In
}
Answer:
181. What will be printed as the result of the operation below?
Garbage values.
main()
Explanation:
{
E
Both the functions suffer from the problem of dangling pointers. In someFun1() temp is
int a=5;
a character array and so the space for it is allocated in heap and is initialized with
character string “string”. This is created dynamically as the function is called, so is also printf(?%d,%d,%d\n?,a,a< <2,a>>2);
AT
deleted dynamically on exiting the function so the string data is not available in the }
calling function main() leading to print some garbage values. The function someFun2() Answer: 5,20,1
also suffers from the same problem but the problem can be easily identified in this
case.
182. What will be printed as the result of the operation below?
#define swap(a,b) a=a+b;b=a-b;a=a-b;
G
s
{ char *ptr1;
int temp; char *ptr2;
or
temp=x; ptr1=(char *)malloc(25);
y=x; ptr2=(char *)malloc(25);
x=temp; strcpy(ptr1,“SC”);
ct
return 0; strcpy(ptr2,“Systems”);
strcat(ptr1,ptr2);
}
ru
printf(“%s”,ptr1);
Answer: 10, 5
10, 5
}
Answer: SCSystems
st
183. What will be printed as the result of the operation below?
main()
186. The following variable is available in file1.c, who can access it?:
{
In
static int average;
char *ptr = “SC Systems”;
Answer: All the functions in the file1.c can access the variable.
*pt++; printf(“%s\n”,pt);
pt++;
187. What will be the result of the following code?
printf(“%s\n”,pt);
E
#define TRUE 0 // some code
while(TRUE)
}
AT
Answer: SC Systems {
s
} main();
}
or
void main() Answer: Till stack overflow
{
int x=10; 191. What is output for the following program?
ct
x++; #include<stdio.h>
changevalue(x); main()
{
ru
x++;
int *p,*q,i;
modifyvalue();
p=(int *)100;
printf(“First output:%d\n”,x);
q=(int *)200;
x++;
st
i=q-p;
changevalue(x);
printf(“%d”,i);
printf(“Second output:%d\n”,x);
}
In
modifyvalue();
a) 100 b) 25 c) 0 d) compile error
printf(“Third output:%d\n”,x);
Answer : b) 25
}
192. What is output for the following program?
E
Answer: 12 , 13 , 13
#include<stdio.h>
#define swap(a,b) temp=a,a=b,b=temp;
189. What will be printed as the result of the operation below?
AT
main()
main()
{
{
int a=5,b=6;
int x=10, y=15;
int temp;
x = x++;
if(a>b)
G
y = ++y;
swap(a,b);
printf(“%d %d\n”,x,y);
printf(“a=%d,b= %d”,a,b);
}
a) a=5 b=6 b) a=6 b=5 c) a=0 b=6 d) None 195. What is output for the following program?
Answer: a) a=5 b=6 #include<stdio.h>
main()
193. What is output for the following program? {
#include<stdio.h> int a=10,b=5;
main() if(a=a&b)
{ b=a^b;
s
unsigned char i; printf(“a=%d,b=%d”,a,b);
for( i=0;i<300;i++) }
or
{ a)a=0,b=5 b)a=10 b=5 c)a=0,b=0 d)none
printf(“*”); Answer: a) a=0,b=5
}
ct
} 196. What is output for the following program?
a)299 b)300 c)infinite d)none #include<stdio.h>
Answer: c) (infinite) main()
ru
{
194. What is output for the following program? int a[5],i,*ip;
#include<stdio.h> for(i=0;i<5;i++)
st
main() a[i]=i;
{ ip=a;
int n=2; printf(“%d”,*(ip+3*sizeof(int)));
In
int sum=5; }
switch(n) a)0 b)5 c)1 d)none
{ Answer: d) none
case 2:sum=sum-2;
E
break; 197. What is the size of the structure?
case 3:sum*=5; #include<stdio.h>
AT
break; main()
default :sum=0; {
} struct
printf(“%d”,sum); {
} char a;
G
s
199. 5-2-3*5-2 evaluates 18 then {
i) - left associative * has precedence over - printf(“%%%%d\r%%%%%”);
or
ii) - right associative * has precedence over - }
iii) * left associative - has precedence over * a) %%%
iv) * right associative - has precedence over * b) %%%%
ct
c) %%%%%
a) i b)ii c) iii d)iv d) None of these
Answer: iv Answer: a) %%%
ru
200. Find the output of the following program. 203. Find the output of the following program.
void main() int v()
st
{ {
float b=1,h=1,a; float m=0;
a=1/2*b*h; return m++;
In
printf(“%.2f”,a); }
} int main()
a) 0.00 {
b) 0.0 printf(“%.7f ”,v());
E
c) 0.50 }
d) 0.5 a) 0.0000000
AT
Answer: a) 0.00 b) 0.00
c) Error
201. Find the output of the following program. d) None
void main() Answer: a) 0.0000000
{
G
static int n[3]; 204. Find the output of the following program.
printf(“%c”,*(n+10)+90); void main()
} {
int i=2,j=1; c) We can’t predict
j>=i; d) Error
printf(“%d”,j); Answer: a) Good
}
a) 1 207. Find the output of the following program.
b) 0 void main()
c) 2 {
s
d) None of these int a=100,b=200;
Answer: a) 1 printf(“%c”,a>b?‘a’:‘b’);
or
}
205. Find the output of the following program. a) b
void main() b) a
ct
{ c) 200
int a=10,b=20; d) 100
a^=b; Answer: a) b
ru
b^=a;
printf(“%d : %d”,a,b); 208. Find the output of the following program.
} void main()
st
a) 10:30 {
b) 30:10 char a=65,b=97;
c) Garbage value if(‘a>‘b’)
In
d) 20:10 printf(“A”)
Answer: b) 30:10 printf(“B”)
}
206. Find the output of the following program. a) AB
E
void main() b) A
{ c) B
AT
int a=10; d) Error
if(!(!a)==!0) Answer: a) AB
printf(“God”);
else 209. What will be the output?
printf(“Good”); void main()
G
} {
a) Good do
b) God {
if(0) int i;
main(); for(i=1;i<4,i++)
printf(“Thaal”); switch(i)
}while(0); case 1: printf(“%d”,i);break;
} {
a) Thaal case 2:printf(“%d”,i);break;
b) Infinite Loop case 3:printf(“%d”,i);break;
s
c) Syntax error }
d) Nothing get printed switch(i) case 4:printf(“%d”,i);
or
Answer: a) Thaal }
Answer: 1,2,3,4
210. For the following C program
ct
#define AREA(x)(3.14*x*x) 213. What will be the output?
main() void main()
{float r1=6.25,r2=2.5,a; {
ru
a=AREA(r1); char *s=“\12345s\n”;
printf(“\n Area of the circle is %f ”, a); printf(“%d”,sizeof(s));
a=AREA(r2); }
st
printf(“\n Area of the circle is %f ”, a); Answer: 6
} 214. What will be the output?
What is the output? void main()
In
Answer: Area of the circle is 122.656250 {
Area of the circle is 19.625000 unsigned i=1; /* unsigned char k= -1 => k=255; */
signed j=-1; /* char k= -1 => k=65535 */
211. What will be the output? /* unsigned or signed int k= -1 =>k=65535 */
E
void main() if(i<j)
{ printf(“less”);
AT
int d=5; else
printf(“%f ”,d); if(i>j)
} printf(“greater”);
Answer: Undefined else
if(i==j)
G
s
1. 1000000 void main()
2. Overflow {
or
3. Error
int i=7;
4. None
printf(“%d”,i++*i++);
Answer: 4
}
ct
Answer: 56
216. A structure pointer is defined of the type time . With 3 fields min,sec hours having pointers to
intergers.
ru
Write the way to initialize the 2nd element to 10. 220. What will be the output?
#define one 0
217. What will be the output? #ifdef one
st
void main() printf(“one is defined ”);
{ #ifndef one
int i=7; printf(“one is not defined ”);
In
printf(“%d”,i++*i++); Answer: “one is defined”
}
Answer: 56 221. What will be the output?
void main()
E
218. int f() {
void main() int count=10,*temp,sum=0;
AT
{ temp=&count;
f(1); *temp=20;
f(1,2); temp=∑
f(1,2,3); *temp=count;
G
} printf(“%d %d %d ”,count,*temp,sum);
f(int i,int j,int k) }
{ Answer: 20 20 20
printf(“%s”,*p++);
222. What is alloca()? printf(“%s”,++*p);
Answer: It allocates and frees memory after use/after getting out of scope. }
Answer: “harma” (p->add(dharma) && (*p)->harma)
223. What will be the output? “harma” (after printing, p->add(hewlett-packard) &&(*p)->harma)
main() “ewlett-packard”
{
s
static i=3; 226. What will be the output?
printf(“%d”,i--); main()
or
return i>0 ? main():0; {int i=0;
} for(i=0;i<20;i++)
Answer: 321 {switch(i)
ct
case 0:i+=5;
224. What will be the output? case 1:i+=2;
char *foo() case 5:i+=5;
ru
{ default i+=4;
char result[100]); break;}
strcpy(result,“anything is good”); printf(“%d,”,i);
st
return(result); }
} }
void main() a) 0,5,9,13,17
In
{ b) 5,9,13,17
char *j; c) 12,17,22
j=foo() d) 16,21
printf(“%s”,j); e) Syntax error
E
} Answer: (d)
Answer: anything is good.
AT
227. What will be the output?
225. What will be the output? main()
void main() {char c=-64;
{ int i=-32
char *s[]={ “dharma”,“hewlett-packard”,“siemens”,“ibm”}; unsigned int u =-16;
G
s
printf(“pass2”); value of x , value of y
else {unsigned int x=-1;
or
printf(“Fail2”) int y;
} y = ~0;
a) Pass1,Pass2 if(x == y)
ct
b) Pass1,Fail2 printf(“same”);
c) Fail1,Pass2 else
d) Fail1,Fail2 printf(“not same”);
ru
e) None of these }
Answer: (c) a) same, MAXINT, -1
b) not same, MAXINT, -MAXINT
st
228. What will the following program do? c) same , MAXUNIT, -1
void main() d) same, MAXUNIT, MAXUNIT
{ e) not same, MAXINT, MAXUNIT
In
int i; Answer: (a)
char a[]=“String”;
char *p=“New Sring”; 230. What will be the result of the following program ?
char *Temp; char *gxxx()
E
Temp=a; {static char xxx[1024];
a=malloc(strlen(p) + 1); return xxx;
AT
strcpy(a,p); //Line number:9// }
p = malloc(strlen(Temp) + 1); main()
strcpy(p,Temp); {char *g=“string”;
printf(“(%s, %s)”,a,p); strcpy(gxxx(),g);
free(p); g = gxxx();
G
free(a); strcpy(g,“oldstring”);
} //Line number 15// printf(“The string is : %s”,gxxx());
a) Swap contents of p & a and print:(New string, string) }
a) The string is : string
b) The string is : Oldstring 234. Find the output for the following C program.
c) Run time error/Core dump #define swap1(a,b) a=a+b;b=a-b;a=a-b;
d) Syntax error during compilation main()
e) None of these {
Answer: (b) int x=5,y=10;
swap1(x,y);
s
231. Find the output for the following C program. printf(“%d %d\n”,x,y);
main() swap2(x,y);
or
{ printf(“%d %d\n”,x,y);
char *p1=“Name”; }
char *p2; int swap2(int a,int b)
ct
p2=(char *)malloc(20); {
while(*p2++=*p1++); int temp;
printf(“%s\n”,p2); temp=a;
ru
} b=a;
Answer: An empty string a=temp;
return;
st
232. Find the output for the following C program. }
main() Answer: 10 5
{
In
int x=20,y=35; 235. Find the output for the following C program.
x = y++ + x++; main()
y = ++y + ++x; {
printf(“%d %d\n”,x,y); char *ptr = “Ramco Systems”;
E
} (*ptr)++;
Answer: 57 94 printf(“%s\n”,ptr);
AT
ptr++;
233. Find the output for the following C program. printf(“%s\n”,ptr);
main() }
{ Answer: Samco Systems
int x=5;
G
printf(“%d %d %d\n”,x,x<<2,x>>2); 236. Find the output for the following C program.
} #include<stdio.h>
Answer: 5 20 1 main()
{
char s1[]=“Ramco”; 240. struct list
char s2[]=“Systems”; {
s1=s2; int x;
printf(“%s”,s1); struct list *next;
} }*head;
Answer: Compilation error giving it cannot be an modifiable ‘lvalue’. the struct head.x =100
s
237. Find the output for the following C program. Is the above assignment to pointer is correct or wrong ?
or
#include<stdio.h> Answer: Wrong
main()
{ 241. What is the output of the following ?
ct
char *p1; main( )
char *p2; { int i;
p1=(char *) malloc(25); i=1;
ru
p2=(char *) malloc(25); i=i+2*i++;
strcpy(p1,“Ramco”); printf(%d,i);
strcpy(p2,“Systems”); }
st
strcat(p1,p2); Answer: 4
printf(“%s”,p1);
} 242. main( )
In
Answer: RamcoSystems {FILE *fp1,*fp2;
fp1=fopen(“one”,“w”)
238. Find the output for the following C program given that fp2=fopen(“one”,“w”)
[1]. The following variable is available in file1.c static int average_float; fputc(‘A’,fp1)
E
Answer: All the functions in the file1.c can access the variable. fputc(‘B’,fp2)
fclose(fp1)
AT
239. Find the output for the following C program. fclose(fp2)
# define TRUE 0 }
some code Find the Error, If Any?
while(TRUE) Answer: No error. But It will over writes on same file.
{
G
s
return (ptr);
244. int z,x=5,y=-10,a=4,b=2; }
or
int main()
z = x++ - --y * b / a;
ct
Choice 1 5 char *x, *y;
Choice 2 6 x = “HELLO”;
Choice 3 10 [Ans] Corrected by buddy by running the program y = myFunc (x);
ru
Choice 4 11 printf (“y = %s \n”, y);
Choice 5 12 return 0;
}
st
245. With every use of a memory allocation function, what function should be used to release
allocated memory which is no longer needed? What will print when the sample code above is executed?
Choice 1 unalloc() Choice 1 y = HELLO
In
Choice 2 dropmem() Choice 2 y = ELLO
Choice 3 dealloc() Choice 3 y = LLO
Choice 4 release() Choice 4 y = LO [Ans]
Choice 5 free() [Ans] Choice 5 x = O
E
248. struct node *nPtr, *sPtr; /* pointers for a linked list. */
246. void *ptr;
AT
for (nPtr=sPtr; nPtr; nPtr=nPtr->next)
myStruct myArray[10];
{
ptr = myArray;
free(nPtr);
Which of the following is the correct way to increment the variable “ptr”?
}
Choice 1 ptr = ptr + sizeof(myStruct); [Ans]
G
Choice 2 ++(int*)ptr; The sample code above releases memory from a linked list. Which of the choices below
accurately describes how it will work?
Choice 3 ptr = ptr + sizeof(myArray);
Choice 1 It will work correctly since the for loop covers the entire list. Choice 4
Choice 2 It may fail since each node “nPtr” is freed before its next address can be A declaration occurs once, but a definition may occur many times. [Ans]
accessed. (Ans) Choice 5
Choice 3 In the for loop, the assignment “nPtr=nPtr->next” should be changed to
Both can occur multiple times, but a definition must occur first.
“nPtr=nPtr.next”.
Choice 4 This is invalid syntax for freeing memory.
252. int testarray[3][2][2] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
Choice 5 The loop will never end.
s
What value does testarray[2][1][0] in the sample code above contain?
249. What function will read a specified number of elements from a file? Choice 1 3
or
Choice 1 fileread() Choice 2 5
Choice 2 getline() Choice 3 7
Choice 3 readfile()
Choice 4 9
ct
Choice 4 fread()(Ans)
Choice 5 11[Ans].
Choice 5 gets().
ru
253. int a=10,b;
250. “My salary was increased by 15%!”
Select the statement which will EXACTLY reproduce the line of text above. b=a++ + ++a;
Choice 1 printf(“%d,%d,%d,%d”,b,a++,a,++a);
st
printf(“\”My salary was increased by 15/%\!\“\n”); What will be the output when following code is executed?
Choice 2 Choice 1 12,10,11,13
printf(“My salary was increased by 15%!\n”); (Ans)
In
Choice 2 22,10,11,13
Choice 3
Choice 3 22,11,11,11
printf(“My salary was increased by 15'%'!\n”);
Choice 4 12,11,11,11
Choice 4
Choice 5 22,13,13,13[Ans].
printf(“\”My salary was increased by 15%%!\“\n”);[Ans]
E
Choice 5
printf(“\”My salary was increased by 15‘%’!\“\n”); 254. int x[] = { 1, 4, 8, 5, 1, 4 };
AT
int *ptr, y;
251. What is a difference between a declaration and a definition of a variable? ptr = x + 4;
Choice 1 y = ptr - x;
Both can occur multiple times, but a declaration must occur first.
What does y in the sample code above equal?
Choice 2
G
Choice 1 -3
There is no difference between them.
Choice 2 0
Choice 3
Choice 3 4[Ans]
A definition occurs once, but a declaration may occur many times.
Choice 4 4 + sizeof( int ) Choice 3 MAX_NUM is a precompiler constant.
Choice 5 4 * sizeof( int ) Choice 4 MAX_NUM is a preprocessor macro. [Ans]
Choice 5 MAX_NUM is an integer constant.
255. void myFunc (int x)
{ 258. Which one of the following will turn off buffering for stdout?
Choice 1 setbuf( stdout, FALSE );
if (x > 0)
Choice 2 setvbuf( stdout, NULL );
myFunc(--x);
s
Choice 3 setbuf( stdout, NULL ); [Ans]
printf(“%d, ”, x);
Choice 4 setvbuf( stdout, _IONBF );
or
Choice 5 setbuf( stdout, _IONBF );
}
int main() 259. What is a proper method of opening a file for writing as binary file?
ct
{ Choice 1 FILE *f = fwrite( “test.bin”, “b” );
myFunc(5); Choice 2 FILE *f = fopenb( “test.bin”, “w” );
return 0; Choice 3 FILE *f = fopen( “test.bin”, “wb” );
ru
} Choice 4 FILE *f = fwriteb( “test.bin” );
What will the above sample code produce when executed? Choice 5 FILE *f = fopen( “test.bin”, “bw” ); [Ans]
Choice 1 1, 2, 3, 4, 5, 5,
st
260. Which one of the following functions is the correct choice for moving blocks of binary data
Choice 2 4, 3, 2, 1, 0, 0, that are of arbitrary size and position in memory?
Choice 3 5, 4, 3, 2, 1, 0, Choice 1 memcpy()
Choice 4 0, 0, 1, 2, 3, 4, [Ans]
In
Choice 2 memset()
Choice 5 0, 1, 2, 3, 4, 5, Choice 3 strncpy()
Choice 4 strcpy()
256. 11 ^ 5 Choice 5 memmove()[Ans]
E
What does the operation shown above produce?
261. int x = 2 * 3 + 4 * 5;
Choice 1 1
What value will x contain in the sample code above?
AT
Choice 2 6 Choice 1 22
Choice 3 8 Choice 2 26[Ans]
Choice 4 14 [Ans] Choice 3 46
Choice 5 15. Choice 4 50
Choice 5 70
G
s
clone = alloca(bytes); Choice 5 None of the above
if (!clone)
or
return clone; 265. Which one of the following provides conceptual support for function calls?
memcpy(clone, a, bytes); Choice 1 The system stack[Ans]
return clone; Choice 2 The data segment
ct
Choice 3 The processor's registers
} Choice 4 The text segment
Choice 5 The heap
ru
The function array_dup(), defined above, contains an error. Which one of the following
correctly analyzes it?
266. C is which kind of language?
Choice 1 If the arguments to memcpy() refer to overlapping regions, the destination
Choice 1 Machine
buffer will be subject to memory corruption.
st
Choice 2 Procedural[Ans]
Choice 2 array_dup() declares its first parameter to be a pointer, when the actual
Choice 3 Assembly
argument will be an array.
Choice 4 Object-oriented
In
Choice 3 The memory obtained from alloca() is not valid in the context of the caller.
Choice 5 Strictly-typed
Moreover, alloca() is nonstandard. [Ans]
Choice 4 size_t is not a Standard C defined type and may not be known to the compiler.
267. int i,j;
Choice 5 The definition of array_dup() is unusual. Functions cannot be defined using
int ctr = 0;
this syntax.
E
int myArray[2][3];
263. int var1; for (i=0; i<3; i++)
AT
If a variable has been declared with file scope, as above, can it safely be accessed globally for (j=0; j<2; j++)
from another file? {
Choice 1 Yes; it can be referenced through the register specifier. myArray[j][i] = ctr;
Choice 2 No; it would have to have been initially declared as a static variable. ++ctr;
}
G
Choice 3 No; it would need to have been initially declared using the global
keyword.[Ans] What is the value of myArray[1][2]; in the sample code above?
Choice 1 1
Choice 4 Yes; it can be referenced through the publish specifier.
Choice 2 2
Choice 5 Yes; it can be referenced through the extern specifier.
Choice 3 3 Choice 3 defg
Choice 4 4 Choice 4 cdefg
Choice 5 5 [Ans] 00,10,01,11,12 Choice 5 None of the above
s
What will be printed when the sample code above is executed? What will the code above print when executed?
or
Choice 1 x=0 ceil =>rounds up 3.2=4 floor =>rounds down 3.2=3
Choice 2 x=1 Choice 1 -3 : 4 -4 : 3 [Ans]
Choice 3 x=3 Choice 2 -4 : 4 -3 : 3
ct
Choice 4 x=4[Ans] Choice 3 -4 : 3 -4 : 3
Choice 5 x=5 Choice 4 -4 : 3 -3 : 4
Choice 5 -3 : 3 -4 : 4
ru
269. int x = 3; 272. Which one of the following will declare a pointer to an integer at address 0x200 in memory?
if( x == 2 ); Choice 1 int *x; *x = 0x200;[Ans]
x = 0; Choice 2 int *x = &0x200;
st
if( x == 3 ) Choice 3 int *x = *0x200;
x++; Choice 4 int *x = 0x200;
else x += 2; Choice 5 int *x( &0x200 );
In
What value will x contain when the sample code above is executed?
Choice 1 1 273. int x = 5;
Choice 2 2[Ans] int y = 2;
Choice 3 3 char op = ‘*’;
E
Choice 4 4 switch (op)
Choice 5 5 {
AT
default : x += 1;
270. char *ptr;
case ‘+’ : x += y; /*It will go to all the cases*/
char myString[] = “abcdefg”;
case ‘-’ : x -= y;
ptr = myString;
}
ptr += 5;
G
What string does ptr point to in the sample code above? After the sample code above has been executed, what value will the variable x contain?
Choice 1 fg [Ans]/*because string*/ Choice 1 4
Choice 2 efg Choice 2 5
Choice 3 6 [Ans]
Choice 4 7 277. All of the following choices represent syntactically correct function definitions. Which one
Choice 5 8 of the following represents a semantically legal function definition in Standard C?
Choice 1 Code:[Ans]
s
x--; if (isdigit(buf[i]))
} cnt++;
or
Referring to the sample code above, what value will the variable counter have when
completed? return cnt;
Choice 1 0 }
ct
Choice 2 1 Choice 2 Code:
Choice 3 2[Ans]
int count_digits (const char * buf) {
Choice 4 3
ru
int cnt = 0;
Choice 5 4
assert(buf != NULL);
for (int i = 0; buf[i] != ‘\0’; i++)
275. char ** array [12][12][12];
st
if (isdigit(buf[i]))
Consider array, defined above. Which one of the following definitions and initializations of p
cnt++;
is valid?
return cnt;
In
Choice 1 char ** (* p) [12][12] = array; [Ans]
}
Choice 2 char ***** p = array;
Choice 3 char * (* p) [12][12][12] = array; Choice 3 Code:
Choice 4 const char ** p [12][12][12] = array;
int count_digits (const char * buf) {
Choice 5 char (** p) [12][12] = array;
E
int cnt = 0, i;
assert(buf != NULL);
276. void (*signal(int sig, void (*handler) (int))) (int);
AT
for (i = 0; buf[i] != ‘\0’; i++)
Which one of the following definitions of sighandler_t allows the above declaration to be if (isdigit(buf[i]))
rewritten as follows:
cnt++;
sighandler_t signal (int sig, sighandler_t handler);
return cnt;
Choice 1 typedef void (*sighandler_t) (int);[Ans]
}
G
s
int count_digits (const char * buf) {
assert(buf != NULL); 281. short testarray[4][3] = { {1}, {2, 3}, {4, 5, 6} };
or
int cnt = 0; printf( “%d\n”, sizeof( testarray ) );
for (int i = 0; buf[i] != ‘\0’; i++)
Assuming a short is two bytes long, what will be printed by the above code?
if (isdigit(buf[i]))
ct
Choice 1 It will not compile because not enough initializers are given.
cnt++;
Choice 2 6
return cnt;
Choice 3 7
}
ru
Choice 4 12
Choice 5 24 [Ans]
278. struct customer *ptr = malloc( sizeof( struct customer ) );
Given the sample allocation for the pointer "ptr" found above, which one of the following
st
282. char buf [] = “Hello world!”;
statements is used to reallocate ptr to be an array of 10 elements?
char * buf = “Hello world!”;
Choice 1 ptr = realloc( ptr, 10 * sizeof( struct customer)); [Ans]
In terms of code generation, how do the two definitions of buf, both presented above, differ?
Choice 2 realloc( ptr, 9 * sizeof( struct customer ) );
In
Choice 1 The first definition certainly allows the contents of buf to be safely modified at
Choice 3 ptr += malloc( 9 * sizeof( struct customer ) ); runtime; the second definition does not.
Choice 4 ptr = realloc( ptr, 9 * sizeof( struct customer ) ); Choice 2 The first definition is not suitable for usage as an argument to a function call;
Choice 5 realloc( ptr, 10 * sizeof( struct customer ) ); the second definition is.
E Choice 3 The first definition is not legal because it does not indicate the size of the array
279. Which one of the following is a true statement about pointers? to be allocated; the second definition is legal.
Choice 1 Pointer arithmetic is permitted on pointers of any type. Choice 4 They do not differ -- they are functionally equivalent. [Ans]
AT
Choice 5 The first definition does not allocate enough space for a terminating NULL
Choice 2 A pointer of type void * can be used to directly examine or modify an object
character, nor does it append one; the second definition does.
of any type.
283. In a C expression, how is a logical AND represented?
Choice 3 Standard C mandates a minimum of four levels of indirection accessible
Choice 1 @@
through a pointer.
G
Choice 2 ||
Choice 4 A C program knows the types of its pointers and indirectly referenced data
Choice 3 .AND.
items at runtime. [Ans] Choice 4 && [Ans]
Choice 5 Pointers may be used to simulate call-by-reference. Choice 5 .AND
284. How do printf()’s format specifiers %e and %f differ in their treatment of floating-point
numbers? int main()
Choice 1 %e always displays an argument of type double in engineering notation; %f {
always displays an argument of type double in decimal notation. [Ans] for( i = 0; i < 10; increment( i ) )
Choice 2 %e expects a corresponding argument of type double; %f expects a {
corresponding argument of type float. }
Choice 3 %e displays a double in engineering notation if the number is very small or printf(“i=%d\n”, i);
s
very large. Otherwise, it behaves like %f and displays the number in decimal return 0;
notation. }
or
Choice 4 %e displays an argument of type double with trailing zeros; %f never displays
What will happen when the program above is compiled and executed?
trailing zeros.
Choice 1 It will not compile.
Choice 5 %e and %f both expect a corresponding argument of type double and format it
Choice 2 It will print out: i=9.
ct
identically. %e is left over from K&R C; Standard C prefers %f for new code.
Choice 3 It will print out: i=10.
Choice 4 It will print out: i=11.
285. Which one of the following Standard C functions can be used to reset end-of-file and error
ru
conditions on an open stream? Choice 5 It will loop indefinitely.[Ans]
Choice 1 clearerr()
Choice 2 fseek()(Ans) 288. char ptr1[] = “Hello World”;
char *ptr2 = malloc( 5 );
st
Choice 3 ferror()
Choice 4 feof() ptr2 = ptr1;
Choice 5 setvbuf() What is wrong with the above code (assuming the call to malloc does not fail)?
In
Choice 1 There will be a memory overwrite.
286. Which one of the following will read a character from the keyboard and will store it in the Choice 2 There will be a memory leak.
variable c? Choice 3 There will be a segmentation fault.
Choice 1 c = getc(); Choice 4 Not enough space is allocated by the malloc. (Ans)
E Choice 5 It will not compile.
Choice 2 getc( &c );
Choice 3 c = getchar( stdin );
Choice 4 getchar( &c ) 289. int i = 4;
AT
Choice 5 c = getchar(); [Ans] switch (i)
287. #include <stdio.h> {
int i; default:
void increment( int i ) ;
G
{ case 3:
i++; i += 5;
} if ( i == 8)
{ 292. How do you include a system header file called sysheader.h in a C source file?
i++; Choice 1 #include <sysheader.h> [Ans]
if (i == 9) break; Choice 2 #incl “sysheader.h”
i *= 2; Choice 3 #includefile <sysheader>
} Choice 4 #include sysheader.h
i -= 4; Choice 5 #incl <sysheader.h>
break;
s
case 8: 293. Which one of the following printf() format specifiers indicates to print a double value in
i += 5; decimal notation, left aligned in a 30-character field, to four (4) digits of precision?
or
break; Choice 1 %-30.4e
} Choice 2 %4.30e
Choice 3 %-4.30f
ct
printf(“i = %d\n”, i); Choice 4 %-30.4f [Ans] decimal notation
What will the output of the sample code above be? Choice 5 %#30.4f
ru
Choice 1 i = 5[Ans]
Choice 2 i = 8 294. int x = 0;
Choice 3 i = 9 for ( ; ; )
{
st
Choice 4 i = 10
Choice 5 i = 18 if (x++ == 4)
break;
continue;
In
290. Which one of the following C operators is right associative?
Choice 1 = [Ans]
Choice 2 , }
Choice 3 [] printf(“x=%d\n”, x);
E
Choice 4 ^ What will be printed when the sample code above is executed?
Choice 5 -> Choice 1 x=0
Choice 2 x=1
AT
Choice 4 It automatically initializes a variable to NULL. of the following three data types: short; int; and long?
Choice 5 It indicates that a variable's memory space is allocated upon entry into the Choice 1 1, 2, 2
block. Choice 2 1, 2, 4
Choice 3 1, 2, 8
Choice 4 2, 2, 4[Ans] z = x / i;
Choice 5 2, 4, 8 printf(“z=%.2f\n”, z);
296. int y[4] = {6, 7, 8, 9}; What will print when the sample code above is executed?
int *ptr = y + 2; Choice 1 z=0.00
printf(“%d\n”, ptr[ 1 ] ); /*ptr+1 == ptr[1]*/ Choice 2 z=1.00[Ans]
Choice 3 z=1.50
s
What is printed when the sample code above is executed? Choice 4 z=2.00
Choice 1 6 Choice 5 z=NULL
or
Choice 2 7
Choice 3 8 300. Which one of the following variable names is NOT valid?
Choice 4 9[Ans] Choice 1 go_cart
ct
Choice 5 The code will not compile. Choice 2 go4it
Choice 3 4season[Ans]
297. penny = one Choice 4 run4
ru
nickel = five Choice 5 _what
dime = ten
quarter = twenty-five 301. int a [8] = { 0, 1, 2, 3 };
st
How is enum used to define the values of the American coins listed above? The definition of a above explicitly initializes its first four elements. Which one of the following
Choice 1 enum coin {(penny,1), (nickel,5), (dime,10), (quarter,25)}; describes how the compiler treats the remaining four elements?
Choice 2 enum coin ({penny,1}, {nickel,5}, {dime,10}, {quarter,25}); Choice 1 Standard C defines this particular behavior as implementation-dependent. The
In
Choice 3 enum coin {penny=1,nickel=5,dime=10,quarter=25};[Ans] compiler writer has the freedom to decide how the remaining elements will be
Choice 4 enum coin (penny=1,nickel=5,dime=10,quarter=25); handled.
Choice 5 enum coin {penny, nickel, dime, quarter} (1, 5, 10, 25); Choice 2 The remaining elements are initialized to zero(0).[Ans]
Choice 3 It is illegal to initialize only a portion of the array. Either the entire array must
E
298. char txt [20] = “Hello world!\0”; be initialized, or no part of it may be initialized.
How many bytes are allocated by the definition above? Choice 4 As with an enum, the compiler assigns values to the remaining elements by
Choice 1 11 bytes counting up from the last explicitly initialized element. The final four elements
AT
s
Choice 2 int *ptr = (int *) calloc(10, sizeof(int)); {
Choice 3 int *ptr = (int *) malloc(10*sizeof(int)); [Ans] ????
or
Choice 4 int *ptr = (int *) alloc(10*sizeof(int)); return x * factorial(x - 1);
Choice 5 int *ptr = (int *) calloc(10*sizeof(int)); }
ct
304. What are two predefined FILE pointers in C? With what do you replace the ???? to make the function shown above return the correct
answer?
Choice 1 stdout and stderr
Choice 1 if (x == 0) return 0;
Choice 2 console and error
ru
Choice 2 return 1;
Choice 3 stdout and stdio [Ans]
Choice 3 if (x >= 2) return 2;
Choice 4 stdio and stderr
Choice 4 if (x == 0) return 1;
Choice 5 errout and conout
Choice 5 if (x <= 1) return 1; [Ans]{more probable}
st
305. u32 X (f32 f)
307. /* Increment each integer in the array ‘p’ of * size ‘n’. */
{
In
union {
void increment_ints (int p [/*n*/], int n)
f32 f;
{
u32 n;
assert(p != NULL); /* Ensure that ‘p’ isn't a null pointer. */
E assert(n >= 0); /* Ensure that ‘n’ is nonnegative. */
} u;
u.f = f; while (n) /* Loop over ‘n’ elements of ‘p’. */
return u.n;
AT
} {
Given the function X(), defined above, assume that u32 is a type-definition indicative of a 32- *p++; /* Increment *p. */
bit unsigned integer and that f32 is a type-definition indicative of a 32-bit floating-point number. p++, n--; /* Increment p, decrement n. */
Which one of the following describes the purpose of the function defined above? }
G
Choice 1 X() effectively rounds f to the nearest integer value, which it returns. }
Choice 2 X() effectively performs a standard typecast and converts f to a roughly Consider the function increment_ints(), defined above. Despite its significant inline
equivalent integer. [Ans] commentary, it contains an error. Which one of the following correctly assesses it?
Choice 1 *p++ causes p to be incremented before the dereference is performed, because The code above comes from header files for the FreeBSD implementation of the C library.
both operators have equal precedence and are right associative. What is the primary purpose of the __P() macro?
Choice 2 An array is a nonmodifiable lvalue, so p cannot be incremented directly. A Choice 1 The __P() macro has no function and merely obfuscates library function
navigation pointer should be used in conjunction with p. declarations. It should be removed from further releases of the C library.
Choice 3 *p++ causes p to be incremented before the dereference is performed, because Choice 2 The __P() macro provides forward compatibility for C++ compilers, which do
the autoincrement operator has higher precedence than the indirection not recognize Standard C prototypes.
operator. (Ans) Choice 3 Identifiers that begin with two underscores are reserved for C library
s
Choice 4 The condition of a while loop must be a Boolean expression. The condition implementations. It is impossible to determine the purpose of the macro from
should be n != 0. the context given.
or
Choice 5 An array cannot be initialized to a variable size. The subscript n should be Choice 4 The __P() macro provides backward compatibility for K&R C compilers,
removed from the definition of the parameter p. which do not recognize Standard C prototypes. [Ans]
Choice 5 The __P() macro serves primarily to differentiate library functions from
ct
308. How is a variable accessed from another file? application-specific functions.
Choice 1 The global variable is referenced via the extern specifier.[Ans]
Choice 2 The global variable is referenced via the auto specifier. 311. Which one of the following is NOT a valid identifier?
ru
Choice 3 The global variable is referenced via the global specifier. Choice 1 __ident
Choice 4 The global variable is referenced via the pointer specifier. Choice 2 auto [Ans]
Choice 5 The global variable is referenced via the ext specifier. Choice 3 bigNumber
st
Choice 4 g42277
309. When applied to a variable, what does the unary “&” operator yield? Choice 5 peaceful_in_space
Choice 1 The variable’s value
In
Choice 2 The variable’s binary form 312. int read_long_string (const char ** const buf) {
Choice 3 The variable’s address [Ans] char * p = NULL;
Choice 4 The variable’s format const char * fwd = NULL;
Choice 5 The variable’s right value size_t len = 0;
E
assert(buf);
310. /* sys/cdef.h */ do
AT
#if defined(__STDC__) || defined(__cplusplus) {
#define __P(protos) protos p = realloc(p, len += 256);
#else if (!p)
#define __P(protos) () return 0;
#endif if (!fwd)
G
/* stdio.h */ fwd = p;
#include <sys/cdefs.h> else
div_t div __P((int, int)); fwd = strchr(p, ‘\0’);
Choice 3 Visible to all translation units
} while (fgets(fwd, 256, stdin)); Choice 4 Read-only subsequent to initialization
*buf = p; Choice 5 Allocated on the heap[Ans]
return 1;
} double read_double (FILE * fp) {
double d;
The function read_long_string(), defined above, contains an error that may be particularly
assert(fp != NULL);
visible under heavy stress. Which one of the following describes it?
s
Choice 1 The write to *buf is blocked by the const qualifications applied to its type.
fscanf(fp, “ %lf ”, d);
or
Choice 2 If the null pointer for char is not zero-valued on the host machine, the implicit
return d;
comparisons to zero (0) may introduce undesired behavior. Moreover, even if
}
successful, it introduces machine-dependent behavior and harms portability.
Choice 3 The symbol stdin may not be defined on some ANCI C compliant systems.
ct
The code above contains a common error. Which one of the following describes it?
Choice 4 The else causes fwd to contain an errant address. (Ans) Choice 1 fscanf() will fail to match floating-point numbers not preceded by whitespace.
Choice 5 If the call to realloc() fails during any iteration but the first, all memory
Choice 2 The format specifier %lf indicates that the corresponding argument should be
ru
previously allocated by the loop is leaked.
long double rather than double. (Ans)
Choice 3 The call to fscanf() requires a pointer as its last argument.
313. FILE *f = fopen( fileName, “r” );
Choice 4 The format specifier %lf is recognized by fprintf() but not by fscanf().
readData( f );
st
Choice 5 d must be initialized prior to usage.
if( ???? )
In
{
puts( “End of file was reached” ); Choice 1 ___S
} Choice 2 1___ [Ans]
Choice 3 ___1
Which one of the following can replace the ???? in the code above to determine if the end of
E Choice 4 ___
a file has been reached?
Choice 1 f == EOF[Ans] Choice 5 S___
AT
Choice 2 feof( f )
Choice 3 eof( f ) 316. According to Standard C, what is the type of an unsuffixed floating-point literal, such as
Choice 4 f == NULL 123.45?
Choice 5 !f Choice 1 long double
314. Global variables that are declared static are ____________. Choice 2 Unspecified
G
Which one of the following correctly completes the sentence above? Choice 3 float[Ans]
Choice 1 Deprecated by Standard C Choice 4 double
Choice 2 Internal to the current translation unit Choice 5 signed float
317. Which one of the following is true for identifiers that begin with an underscore? 321. short int x; /* assume x is 16 bits in size */
Choice 1 They are generally treated differently by preprocessors and compilers from What is the maximum number that can be printed using printf("%d\n", x), assuming that x is
initialized as shown above?
other identifiers.
Choice 1 127
Choice 2 They are case-insensitive. (Ans)
Choice 2 128
Choice 3 They are reserved for usage by standards committees, system implementers,
Choice 3 255
and compiler engineers.
Choice 4 32,767 [Ans]
Choice 4 Applications programmers are encouraged to employ them in their own code
s
Choice 5 65,536
in order to mark certain symbols for internal usage.
or
Choice 5 They are deprecated by Standard C and are permitted only for backward
322. void crash (void)
compatibility with older C libraries. {
printf(“got here”);
ct
318. Which one of the following is valid for opening a read-only ASCII file? *((char *) 0) = 0;
Choice 1 fileOpen (filenm, “r”);
Choice 2 fileOpen (filenm, “ra”); }
ru
Choice 3 fileOpen (filenm, “read”);
The function crash(), defined above, triggers a fault in the memory management hardware
Choice 4 fopen (filenm, “read”);
for many architectures. Which one of the following explains why "got here" may NOT be
Choice 5 fopen (filenm, “r”);[Ans] printed before the crash?
st
Choice 1 The C standard says that dereferencing a null pointer causes undefined
319. f = fopen( filename, “r” ); behavior. This may explain why printf() apparently fails.
Referring to the code above, what is the proper definition for the variable f? Choice 2 If the standard output stream is buffered, the library buffers may not be
In
Choice 1 FILE f; flushed before the crash occurs. (Ans)
Choice 2 FILE *f;[Ans] Choice 3 printf() always buffers output until a newline character appears in the buffer.
Choice 3 int f; Since no newline was present in the format string, nothing is printed.
Choice 4 struct FILE f; Choice 4 There is insufficient information to determine why the output fails to appear.
E
Choice 5 char *f; A broader context is required.
Choice 5 printf() expects more than a single argument. Since only one argument is
AT
320. If there is a need to see output as soon as possible, what function will force the output from given, the crash may actually occur inside printf(), which explains why the
the buffer into the output stream? string is not printed. puts() should be used instead.
Choice 1 flush()
Choice 2 output()(Ans) 323. char * dwarves [] = {
Choice 3 fflush() “Sleepy”,
G
How many elements does the array dwarves (declared above) contain? Assume the C
326. char *buffer = “0123456789”;
compiler employed strictly complies with the requirements of Standard C.
char *ptr = buffer;
Choice 1 4
ptr += 5;
Choice 2 5[Ans]
printf( “%s\n”, ptr );
Choice 3 6
s
printf( “%s\n”, buffer );
Choice 4 7
or
Choice 5 8 What will be printed when the sample code above is executed?
Choice 1 0123456789 56789
324. Which one of the following can be used to test arrays of primitive quantities for strict equality Choice 2 5123456789 5123456789
under Standard C?
ct
Choice 3 56789 56789
Choice 1 qsort()
Choice 4 0123456789 0123456789
Choice 2 bcmp() [Ans]
Choice 5 56789 0123456789 [Ans]
Choice 3 memcmp()
ru
Choice 4 strxfrm()
327. char * get_rightmost (const char * d)
Choice 5 bsearch()
{
st
char rightmost [MAXPATHLEN];
325. int debug (const char * fmt, ...) {
const char * p = d;
extern FILE * logfile;
assert(d != NULL);
va_list args;
In
while (*d != ‘\0’)
assert(fmt);
{
args = va_arg(fmt, va_list);
if (*d == ‘/’)
return vfprintf(logfile, fmt, args);
p = (*(d + 1) != ‘\0’) ? d + 1 : p;
}
E
d++;
The function debug(), defined above, contains an error. Which one of the following describes
}
it?
memset(rightmost, 0, sizeof(rightmost));
AT
Choice 1 The ellipsis is a throwback from K&R C. In accordance with Standard C, the
memcpy(rightmost, p, strlen(p) + 1);
declaration of args should be moved into the parameter list, and the K&R C
return rightmost;
macro va_arg() should be deleted from the code.
}
Choice 2 vfprintf() does not conform to ISO 9899: 1990, and may not be portable.
Choice 3 Library routines that accept argument lists cause a fault on receipt of an empty The function get_rightmost(), defined above, contains an error. Which one of the following
G
list. The argument list must be validated with va_null() before invoking describes it?
vfprintf(). Choice 1 The calls to memset() and memcpy() illegally perform a pointer conversion on
Choice 4 The argument list args has been improperly initialized. [Ans] rightmost without an appropriate cast.
Choice 2 The code does not correctly handle the situation where a directory separator '/' Choice 4 Variable definition must precede variable declaration.
is the final character. [Ans] Choice 5 There is no difference in C between variable declaration and variable
Choice 3 The if condition contains an incorrectly terminated character literal. definition.
Choice 4 memcpy() cannot be used safely to copy string data.
Choice 5 The return value of get_rightmost() will be invalid in the caller’s context. 331. int x[] = {1, 2, 3, 4, 5};
int u;
328. What number is equivalent to -4e3?
s
int *ptr = x;
Choice 1 -4000 [Ans] ????
or
Choice 2 -400 for( u = 0; u < 5; u++ )
Choice 3 -40 {
Choice 4 .004 printf(“%d-”, x[u]);
ct
Choice 5 .0004 }
printf( “\n” );
329. void freeList( struct node *n ) Which one of the following statements could replace the ???? in the code above to cause the
ru
{ string 1-2-3-10-5- to be printed when the code is executed?
while( n ) Choice 1 *ptr + 3 = 10;
{ Choice 2 *ptr[ 3 ] = 10;
st
???? Choice 3 *(ptr + 3) = 10;[Ans]
} Choice 4 (*ptr)[ 3 ] = 10;
} Choice 5 *(ptr[ 3 ]) = 10;
In
Which one of the following can replace the ???? for the function above to release the
memory allocated to a linked list? 332. /*sum_array() has been ported from FORTRAN. No * logical changes have been made*/
Choice 1 n = n->next; free( n ); double sum_array(double d[],int n)
Choice 2 struct node m = n; n = n->next; free( m ); {
E
Choice 3 struct node m = n; free( n ); n = m->next; register int i;
Choice 4 free( n ); n = n->next; [Ans] double total=0;
AT
Choice 5 struct node m = n; free( m ); n = n->next; (Ans) assert(d!=NULL);
for(i=l;i<=n;i++)
330. How does variable definition differ from variable declaration?
total+=d[i];
Choice 1 Definition allocates storage for a variable, but declaration only informs the
return total;
compiler as to the variable’s type.
G
}
Choice 2 Declaration allocates storage for a variable, but definition only informs the
compiler as to the variable’s type. The function sum_array(), defined above, contains an error. Which one of the following
Choice 3 Variables may be defined many times, but may be declared only once.[Ans] accurately describes it?
Choice 1 The range of the loop does not match the bounds of the array d. {
Choice 2 The loop processes the incorrect number of elements. default:
Choice 3 total is initialized with an integer literal. The two are not compatible in an return (fibonacci(n - 1) + fibonacci(n - 2));
assignment. [Ans]
Choice 4 The code above fails to compile if there are no registers available for i. case 1:
Choice 5 The formal parameter d should be declared as double * d to allow dynamically case 2:
allocated arrays as arguments. }
s
return 1;
}
or
333. #include <stdio.h>
void func() The function above has a flaw that may result in a serious error during some invocations.
{ Which one of the following describes the deficiency illustrated above?
int x = 0; Choice 1 For some values of n, the environment will almost certainly exhaust its stack
ct
static int y = 0; space before the calculation completes.[Ans]
Choice 2 An error in the algorithm causes unbounded recursion for all values of n.
Choice 3 A break statement should be inserted after each case. Fall-through is not
ru
x++; y++;
printf( “%d -- %d\n”, x, y ); desirable here.
} Choice 4 The fibonacci() function includes calls to itself. This is not directly supported
by Standard C due to its unreliability.
st
int main() Choice 5 Since the default case is given first, it will be executed before any case
{ matching n.
In
func();
func(); 335. When applied to a variable, what does the unary “&” operator yield?
Choice 2 128
334. int fibonacci (int n)
Choice 3 255
{
Choice 4 32,767[Ans]
switch (n)
Choice 5 65,536
Choice 3 %e always displays an argument of type double in engineering notation; %f
337. int x = 011 | 0x10; always displays an argument of type double in decimal notation. [Ans]
What value will x contain in the sample code above? Choice 4 %e expects a corresponding argument of type double; %f expects a
Choice 1 3 corresponding argument of type float.
Choice 2 13 [Ans] Choice 5 %e and %f both expect a corresponding argument of type double and format it
Choice 3 19 identically. %e is left over from K&R C; Standard C prefers %f for new code.
Choice 4 25
s
Choice 5 27 341. $$Except 1 all choices are O.K.$$
338. Which one of the following calls will open the file test.txt for reading by fgetc? c = getchar();
or
Choice 1 fopen( “test.txt”, “r” ); What is the proper declaration for the variable c in the code above?
Choice 2 read( “test.txt” ) Choice 1 char *c;
Choice 3 fileopen( “test.txt”, “r” ); [Ans] Choice 2 unsigned int c;
ct
Choice 4 fread( “test.txt” ) Choice 3 int c;
Choice 5 freopen( “test.txt” ) Choice 4 unsigned char c;
Choice 5 char c;[Ans]
ru
339. int m = – 14; 342. Which one of the following will define a function that CANNOT be called from another
int n = 6; source file?
int o; Choice 1 void function() { ... }
st
o = m % ++n; Choice 2 extern void function() { ... }
n += m++ – o; Choice 3 const void function() { ... }
Choice 4 private void function() { ... } [Ans]
In
m <<= (o ^ n) & 3;
Choice 5 static void function() { ... }
Assuming two’s-complement arithmetic, which one of the following correctly represents the
values of m, n, and o after the execution of the code above?
Choice 1 m = – 26, n = – 7, o = 0
Choice 2 m = – 52, n = – 4, o = – 2 (Ans)
E
Choice 3 m = – 26, n = – 5, o = – 2
Choice 4 m = – 104, n = – 7, o = 0
AT
Choice 5 m = – 52, n = – 6, o = 0
340. How do printf()’s format specifiers %e and %f differ in their treatment of floating-point
numbers?
Choice 1 %e displays an argument of type double with trailing zeros; %f never displays
G
trailing zeros.
Choice 2 %e displays a double in engineering notation if the number is very small or
very large. Otherwise, it behaves like %f and displays the number in decimal
notation.