85.
main(){
int i=10,j=20;
j
= i, j?(i,j)?i:j:j;
printf("%d
%d",i,j);
}
Answer:
10 10
Explanation:
The Ternary
operator ( ? : ) is equivalent for if-then-else statement. So the question can
be written as:
if(i,j){
if(i,j)
j
= i;
else
j
= j;
}
else
j
= j;
86.
1. const char *a;
2. char* const a;
3. char const *a;
-Differentiate the above declarations.
Answer:
1. 'const' applies to char * rather
than 'a' ( pointer to a constant char )
*a='F' : illegal
a="Hi" : legal
2. 'const' applies
to 'a' rather than to the value of a
(constant pointer to char )
*a='F' : legal
a="Hi" : illegal
3. Same as 1.
87.
main(){
int i=5,j=10;
i=i&=j&&10;
printf("%d
%d",i,j);
}
Answer:
1 10
Explanation:
The expression can
be written as i=(i&=(j&&10)); The inner expression (j&&10)
evaluates to 1 because j==10. i is 5. i = 5&1 is 1. Hence the result.
88.
main(){
int i=4,j=7;
j
= j || i++ && printf("YOU CAN");
printf("%d
%d", i, j);
}
Answer:
4 1
Explanation:
The
boolean expression needs to be evaluated only till the truth value of the
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) will not be evaluated. So the
remaining expression is not evaluated and so the value of i remains the same.
Similarly when
&& operator is involved in an expression, when any of the operands
become false, the whole expression’s truth value becomes false and hence the
remaining expression will not be evaluated.
false
&& (anything) => false where (anything) will not be evaluated.
89.
main(){
register int
a=2;
printf("Address
of a = %d",&;
printf("Value
of a = %d",;
}
Answer:
Compier Error:
'&' on register variable
Rule to Remember:
& (address of ) operator cannot be applied
on register variables.
90.
main(){
float i=1.5;
switch(i){
case
1: printf("1");
case
2: printf("2");
default
: printf("0");
}
}
Answer:
Compiler Error:
switch expression not integral
Explanation:
Switch statements
can be applied only to integral types.
91.
main(){
extern i;
printf("%d\n",i);{
int
i=20;
printf("%d\n",i);
}
}
Answer:
Linker Error :
Unresolved external symbol i
Explanation:
The identifier i is
available in the inner block and so using extern has no use in resolving it.
92.
main(){
int a=2,*f1,*f2;
f1=f2=&a;
*f2+=*f2+=a+=2.5;
printf("\n%d
%d %d",a,*f1,*f2);
}
Answer:
16 16 16
Explanation:
f1 and f2 both
refer to the same memory location a. So changes through f1 and f2 ultimately
affects only the value of a.
93.
main(){
char
*p="GOOD";
char
a[ ]="GOOD";
printf("\n sizeof(p)
= %d, sizeof(*p) = %d, strlen(p) = %d", sizeof(p), sizeof(*p), strlen(p));
printf("\n
sizeof( = %d, strlen( = %d", sizeof(, strlen();
}
Answer:
sizeof(p)
= 2, sizeof(*p) = 1, strlen(p) = 4
sizeof(
= 5, strlen( = 4
Explanation:
sizeof(p) =>
sizeof(char*) => 2
sizeof(*p)
=> sizeof(char) => 1
Similarly,
sizeof(
=> size of the character array => 5
When
sizeof operator is applied to an array it returns the sizeof the array and
it is not the same as the sizeof the pointer variable. Here the sizeof( where a
is the character array and the size of the array is 5 because the space
necessary for the terminating NULL character should also be taken into account.
94.
#define DIM( array, type)
sizeof(array)/sizeof(type)
main(){
int arr[10];
printf(“The
dimension of the array is %d”, DIM(arr, int));
}
Answer:
10
Explanation:
The size of integer array of 10 elements is 10 *
sizeof(int). The macro expands to sizeof(arr)/sizeof(int) => 10 *
sizeof(int) / sizeof(int) => 10.
95.
int DIM(int array[]) {
return
sizeof(array)/sizeof(int );
}
main(){
int
arr[10];
printf(“The
dimension of the array is %d”, DIM(arr));
}
Answer:
1
Explanation:
Arrays
cannot be passed to functions as arguments and only the pointers can be passed.
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) that happens to be equal in this case.
96.
main(){
static
int a[3][3]={1,2,3,4,5,6,7,8,9};
int
i,j;
static
*p[]={a,a+1,a+2};
for(i=0;i<3;i++){
for(j=0;j<3;j++)
printf("%d\t%d\t%d\t%d\n",*(*(p+i)+j),
*(*(j+p)+i),*(*(i+p)+j),*(*(p+j)+i));
}
}
Answer:
1 1
1 1
2 4
2 4
3 7
3 7
4 2
4 2
5 5
5 5
6 8 6
8
7 3
7 3
8 6
8 6
9 9
9 9
Explanation:
*(*(p+i)+j) is
equivalent to p[i][j].
97.
main(){
void swap();
int
x=10,y=8;
swap(&x,&y);
printf("x=%d
y=%d",x,y);
}
void swap(int *a, int *b){
*a
^= *b, *b ^= *a, *a ^= *b;
}
Answer:
x=10 y=8
Explanation:
Using ^ like this
is a way to swap two variables without using a temporary variable and that too
in a single statement.
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 error
by the call swap(&x,&y); that has two arguments.
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()
int *a, int *b{
*a ^= *b, *b ^= *a, *a ^= *b;
}
where the arguments
follow the (). So naturally the declaration for swap will look like, void
swap() which means the swap can take any number of arguments.
98.
main(){
int i = 257;
int
*iPtr = &i;
printf("%d
%d", *((char*)iPtr), *((char*)iPtr+1) );
}
Answer:
1 1
Explanation:
The integer value
257 is stored in the memory as, 00000001 00000001, so the individual bytes are
taken by casting it to char * and get printed.
99.
main(){
int i = 258;
int
*iPtr = &i;
printf("%d
%d", *((char*)iPtr), *((char*)iPtr+1) );
}
Answer:
2 1
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 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: 00000001 00000010.
100.main(){
int i=300;
char
*ptr = &i;
*++ptr=2;
printf("%d",i);
}
Answer:
556
Explanation:
The integer value
300 in binary notation is: 00000001 00101100.
It is stored in memory (small-endian)
as: 00101100 00000001. Result of the expression *++ptr = 2 makes the memory
representation as: 00101100 00000010. So the integer corresponding to it is
00000010 00101100 => 556.
101.main()
{
char
* str = "hello";
char
* ptr = str;
char
least = 127;
while
(*ptr++)
least = (*ptr
printf("%d",least);
}
Answer:
0
Explanation:
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.
102.
Declare an array of N
pointers to functions returning pointers to functions
returning pointers to characters?
Answer:
(char*(*)( ))
(*ptr[N])( );
103.main(){
struct
student {
char
name[30];
struct
date dob;
}stud;
struct
date{
int
day,month,year;
};
scanf("%s%d%d%d",
stud.rollno, &student.dob.day, &student.dob.month, &student.dob.year);
}
Answer:
Compiler Error:
Undefined structure date
Explanation:
Inside the struct
definition of ‘student’ the member of type struct date is given. The compiler
doesn’t have the definition of date structure (forward reference is not allowed in C in this case)
so it issues an error.
104.main(){
struct
date;
struct
student{
char
name[30];
struct
date dob;
}stud;
struct
date{
int day,month,year;
};
scanf("%s%d%d%d",
stud.rollno, &student.dob.day, &student.dob.month,
&student.dob.year);
}
Answer:
Compiler Error:
Undefined structure date
Explanation:
Only declaration of
struct date is available inside the structure definition of ‘student’ but to
have a variable of type struct date the definition of the structure is
required.
105.
There were 10 records
stored in “somefile.dat” but the following program printed 11
names. What went wrong?
void
main(){
struct
student{
char
name[30], rollno[6];
}stud;
FILE
*fp = fopen(“somefile.dat”,”r”);
while(!feof(fp))
{
fread(&stud,
sizeof(stud), 1 , fp);
puts(stud.name);
}
}
Explanation:
fread reads 10
records and prints the names successfully. It will return EOF only when 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 comes out of the while loop.
106.Is there any
difference between the two declarations,
1. int
foo(int *arr[]) and
2. int
foo(int *arr[2])
Answer:
No
Explanation:
Functions can only
pass pointers and not arrays. The numbers that are allowed inside the [] is just
for more readability. So there is no difference between the two declarations.
107.What is the
subtle error in the following code segment?
void fun(int n, int arr[]){
int
*p=0;
int
i=0;
while(i++
p
= &arr[i];
*p
= 0;
}
Answer & Explanation:
If the body of the
loop never executes p is assigned no address. So p remains NULL where *p =0 may
result in problem (may rise to runtime error “NULL pointer assignment” and
terminate the program).
108.What is wrong
with the following code?
int *foo(){
int
*s = malloc(sizeof(int)100);
assert(s
!= NULL);
return
s;
}
Answer & Explanation:
assert macro should
be used for debugging and finding out bugs. The check s != NULL is for
error/exception handling and for that assert shouldn’t be used. A plain if and
the corresponding remedy statement has to be given.
109.What is the
hidden bug with the following statement?
assert(val++ != 0);
Answer & Explanation:
Assert macro is
used for debugging and removed in release version. In assert, the experssion
involves side-effects. So the behavior of the code becomes different in case of
debug version and the release version thus leading to a subtle bug.
Rule to Remember:
Don’t
use expressions that have side-effects in assert statements.
110.void
main(){
int
*i = 0x400; // i points to the address
400
*i
= 0; // set the value
of memory location pointed by i;
}
Answer:
Undefined behavior
Explanation:
The second
statement results in undefined behavior because it points to some location
whose value may not be available for modification. This type of pointer in which the
non-availability of the implementation of the referenced location is known as
'incomplete type'.
111.#define
assert(cond) if(!(cond)) \
(fprintf(stderr, "assertion failed: %s, file %s, line %d
\n",#cond,\
__FILE__,__LINE__), abort())
void main(){
int
i = 10;
if(i==0)
assert(i
< 100);
else
printf("This
statement becomes else for if in assert macro");
}
Answer:
No output
Explanation:
The else part in
which the printf is there becomes the else for if in the assert macro. Hence
nothing is printed. The solution is to
use conditional operator instead of if statement
#define assert(cond) ((cond)?(0):
(fprintf (stderr, "assertion failed: \ %s, file %s, line %d
\n",#cond, __FILE__,__LINE__), abort()))
Note:
However this
problem of “matching with nearest else” cannot be solved by the usual method of
placing the if statement inside a block like this,
#define
assert(cond) { \
if(!(cond)) \
(fprintf(stderr, "assertion failed: %s,
file %s, line %d \n",#cond,\
__FILE__,__LINE__), abort()) \
}
112.Is the following
code legal?
struct a {
int
x;
struct a b;
}
Answer:
No
Explanation:
Is it 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.
113.Is the following
code legal?
struct a {
int
x;
struct a *b;
}
Answer:
Yes.
Explanation:
*b is a pointer to
type struct a and so is legal. The compiler knows, the size of the 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.
114.Is the following
code legal?
typedef struct a {
int
x;
aType
*b;
}aType;
Answer:
No
Explanation:
The typename aType
is not known at the point of declaring the structure (forward references are
not made for typedefs).
115.Is the following
code legal?
typedef struct a aType;
struct a{
int
x;
aType
*b;
};
Answer:
Yes
Explanation:
The typename aType
is known at the point of declaring the structure, because it is already
typedefined.
116.Is the following
code legal?
void main(){
typedef
struct a aType;
aType someVariable;
struct
a {
int
x;
aType
*b;
};
}
Answer:
No
Explanation:
When the
declaration,typedef struct a aType; is encountered body of struct a is not
known. This is known as ‘incomplete types’.
117.void
main(){
printf(“sizeof
(void *) = %d \n“, sizeof( void *));
printf(“sizeof
(int *) = %d \n”, sizeof(int *));
printf(“sizeof
(double *) = %d \n”, sizeof(double *));
printf(“sizeof(struct
unknown *) = %d \n”, sizeof(struct unknown *));
}
Answer:
sizeof (void *) = 2
sizeof (int *) = 2
sizeof (double
*) =
2
sizeof(struct
unknown *) = 2
Explanation:
The pointer to any
type is of same size.
118.char
inputString[100] = {0};
To get string input from the keyboard which one of the
following is better?
1)
gets(inputString)
2)
fgets(inputString, sizeof(inputString), fp)
Answer & Explanation:
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 as gets but is safe.
119.Which version do
you prefer of the following two,
1)
printf(“%s”,str); // or the
more curt one
2) printf(str);
Answer & Explanation:
Prefer the first
one. If the str contains any format
characters like %d then it will result in a subtle bug.
120.void
main(){
int
i=10, j=2;
int
*ip= &i, *jp = &j;
int
k = *ip/*jp;
printf(“%d”,k);
}
Answer:
Compiler Error:
“Unexpected end of file in comment started in line 5”.
Explanation:
The programmer
intended to divide two integers, but by the “maximum munch” rule, the compiler
treats the operator sequence / and * as /* which happens to be the starting of
comment. To force what is intended by the programmer,
int k = *ip/ *jp;
// give space
explicity separating / and *
//or
int k = *ip/(*jp);
// put braces to
force the intention
will solve the
problem.
121.void
main(){
char
ch;
for(ch=0;ch<=127;ch++)
printf(“%c %d \n“, ch, ch);
}
Answer:
Implementaion
dependent
Explanation:
The char type may
be signed or unsigned by default. If it is signed then ch++ is executed after
ch reaches 127 and rotates back to -128. Thus ch is always smaller than 127.
122.Is this code
legal?
int *ptr;
ptr = (int *) 0x400;Answer:
Yes
Explanation:
The pointer ptr
will point at the integer in the memory location 0x400.
123.main(){
char
a[4]="HELLO";
printf("%s",;
}
Answer:
Compiler error:
Too many initializers
Explanation:
The array a is of
size 4 but the string constant requires 6 bytes to get stored.
124.main(){
char
a[4]="HELL";
printf("%s",;
}
Answer:
HELL%@!~@!@???@~~!
Explanation:
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
and continues to print garbage values till it accidentally comes across a NULL
character.
125.main(){
int a=10,*j;
void
*k;
j=k=&a;
j++;
k++;
printf("\n %u %u ",j,k);
}
Answer:
Compiler error: Cannot
increment a void pointer
Explanation:
Void pointers are
generic pointers and they can be used only when the type is not 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.
126.Printf can be
implemented by using __________ list.
Answer:
Variable length
argument lists
127. char
*someFun(){
char
*temp = “string constant";
return
temp;
}
int
main(){
puts(someFun());
}
Answer:
string
constant
Explanation:
The program suffers no problem
and gives the output correctly because the character constants are stored in
code/data area and not allocated in stack, so this doesn’t lead to dangling
pointers.
128.char
*someFun1(){
char
temp[ ] = “string";
return
temp;
}
char
*someFun2(){
char
temp[ ] = {‘s’, ‘t’,’r’,’i’,’n’,’g’};
return
temp;
}
int
main(){
puts(someFun1());
puts(someFun2());
}
Answer:
Garbage values.
Explanation:
Both the functions
suffer from the problem of dangling pointers. In someFun1() temp is 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 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() also suffers from the same problem but
the problem can be easily identified in this case.
129.Explain Internal
linkage.
Internal linkage
means that all declarations of the identifier within one source file refer to a
single entity but declarations of the same identifier in other source files
refer to different entities.
130.Can the formal
parameter to a function be declared static?
No, because
arguments are always passed on the stack to support recursion.
131.What is an
lvalue?
Something that
can appear on the left side of the "=" sign, it identifies a place
where the result can be stored. For example, in the equation a=b+25, a is an
lvalue.
In the equation
b+25=a, b+25 cannot be used as an lvalue, because it does not identify a
specific place. Hence the above assignment is illegal.
132.Every expression
that is an lvalue, is also an rvalue. Is the reverse true?
No, lvalue denotes
a place in the computer's memory. An rvalue denotes a value, so it can only be
used on the right hand side of an assignment.
133.What
happens if indirection is performed on a NULL pointer?
On some machines
the indirection accesses the memory location zero. On other machines
indirection on a NULL pointer cause a fault that terminate the program. Hence
the result is implementation dependent.
134.Is
the statement legal? d=10-*d.
Illegal because it
specifies that an integer quantity (10-*d) be stored in a pointer variable
135.What does the
below indicate?
int *func(void)
a. void
indicates that there aren't any arguments.
b. there
is one argument of type void.
Answer: a
136.What
are data type modifiers?
To extend the data handling
power, C adds 4 modifiers which may only be applied to char and int. They are
namely signed, unsigned, long and short. Although long may also be applied to
double.
137.Interpret
the meaning of the following.
a. “ab”,”a+b”
b. “w+t”
Answer:
"ab","a+b"->open
a binary file for appending
"w+t"
->create a text file for reading and writing.
138.What
is NULL in the context of files?
In using files, if
any error occurs, a NULL pointer is returned.
139.What
is Register storage class?
It concerns itself
with storing data in the registers of the microprocessor and not in memory. The
value of the variable doesn't have to be loaded freshly from memory every time.
It's important to realize that this a request to the compiler and not a
directive. The compiler may not be able to do it. Since the registers are
normally of 16 bits long, we can use the register storage class for ints and
char's.
140.What
is an assertion statement?
They are actually
macros. They test statements you pass to them and if the statement is false,
they halt the program and inform you that the assertion failed. It is defined
in the header file .
141.Parse
int *(*(*(*abc)())[6])();
abc is a pointer to
a function returning a pointer to array of pointer to functions returning
pointer to integer.
(a) semicolon (b) colon (c) period (d) exclamation mark ans:a)
2. What is false about the following -- A compound statement is
(a) A set of simple statements (b) Demarcated on either side by curly brackets
(c) Can be used in place of simple statement (d) A C function is not a compound statement.
Ans)c
3. What is true about the following C Functions
(a) Need not return any value (b) Should always return an integer
(c) Should always return a float (d) Should always return more than one value
Ans) a
4. Main must be written as
(a) The first function in the program (b) Second function in the program
(c) Last function in the program (d) Any where in the program
Ans)d
5. Which of the following about automatic variables within a function is correct ?
(a) Its type must be declared before using the variable (b) They are local
(c) They are not initialized to zero (d) They are global
Ans)a?
6. Write one statement equivalent to the following two statements: x=sqr(a); return(x);
Choose from one of the alternatives
(a) return(sqr(a)); (b) printf("sqr(a)");
(c) return(a*a*a); (d) printf("%d",sqr(a));
Ans)a
7. Which of the following about the C comments is incorrect ?
(a) Comments can go over multiple lines
(b) Comments can start any where in the line
(c) A line can contain comments with out any language statements
(d) Comments can occur within comments
Ans)d nested comments are not allowed
8. What is the value of y in the following code?
x=7;
y=0;
if(x=6) y=7;
else y=1;
(a) 7 (b) 0 (c) 1 (d) 6
Ans)a used = instead of ==
9. Read the function conv() given below
conv(int t)
{
int u;
u=5/9 * (t-32);
return(u);
}
What is returned
(a) 15 (b) 0 (c) 16.1 (d) 29
10. Which of the following represents true statement either x is in the range of 10 and 50 or y is zero
(a) x >=10 && x <= 50 || y = = 0 (b) x<50
(c) y!=10 && x >= 50 (d) None of these
Ans)a
11. Which of the following is not an infinite loop ?
(a) while(1)\{ ....} (b) for(;;){...}
(c) x=0; (d) # define TRUE 0
do{ /*x unaltered within the loop*/ ...
.....}while(x = = 0); while(TRUE){ ....}
Ans)b?
12. What does the following function print?
func(int i)
{
if(i%2)return 0;
else return 1;
}
main()
{
int =3;
i=func(i);
i=func(i);
printf("%d",i);
}
(a) 3 (b) 1 (c) 0 (d) 2
13. How does the C compiler interpret the following two statements
p=p+x;
q=q+y;
(a) p= p+x; (b)p=p+xq=q+y; (c)p= p+xq; (d)p=p+x/q=q+y;
q=q+y; q=q+y;
For questions 14,15,16,17 use the following alternatives:
a.int b.char c.string d.float
14. '9'
15. "1 e 02"
16. 10e05
17. 15
18. Read the folllowing code
# define MAX 100
# define MIN 100
....
....
if(x>MAX)
x=1;
else if(x
x=50;
if the initial value of x=200,what is the value after executing this code?
(a) 200 (b) 1 (c) -1 (d) 50
19. A memory of 20 bytes is allocated to a string declared as char *s then the following two statements are executed:
s="Entrance"
l=strlen(s);
what is the value of l ?
(a)20 (b)8 (c)9 (d)21
20. Given the piece of code
int a[50];
int *pa;
pa=a;
To access the 6th element of the array which of the following is incorrect?
(a) *(a+5) (b) a[5] (c) pa[5] (d) *(*pa + 5}
Ans)a
21. Consider the following structure:
struct num nam
{
int no;
char name[25];
}
struct num nam n1[]={{12,"Fred"},{15,"Martin"},{8,"Peter"},{11,Nicholas"}};
.....
.....
printf("%d%d",n1[2],no,(*(n1 + 2),no) + 1);
What does the above statement print?
(a) 8,9 (b) 9,9 (c) 8,8 (d) 8,unpredictable value
22. Identify the in correct expression
(a)a=b=3=4; (b)a=b=c=d=0; (c)float a=int b= 3.5; (d)int a; floatb;a=b=3.5;
Ans) b
23. Regarding the scope of the varibles;identify the incorrect statement:
(a) automatic variables are automatically initialized to 0 (b) static variables are are automatically initialized to 0
(c) the address of a register variable is not accessible (d) static variables cannot be initialized with any expression
24. cond 1?cond 2?cond 3?:exp 1:exp 2:exp 3:exp 4;
is equivalent to which of the following?
(a) if cond 1
exp 1;
else if cond 2
exp 2;
else if cond 3
exp 3;
else exp 4;
(b) if cond 1
if cond 2
if cond 3
exp 1;
else exp 2;
else exp 3;
else exp 4;
(c) if cond 1 && cond 2 && cond 3
exp 1 |exp 2|exp 3|exp 4;
(d) if cond 3
exp 1;
else if cond 2 exp 2;
else if cond 3 exp 3;
else exp 4;
25. The operator for exponentiation is
(a) ** (b) ^ (c) % (d) not available
Ans )d
26. Which of the following is invalid
(a) a+=b (b) a*=b (c) a>>=b (d) a**=b
27. What is y value of the code if input x=10
y=5;
if (x==10)
else if(x==9)
else y=8;
(a)9 (b)8 (c)6 (d)7
28. What does the following code do?
fn(int n, int p, int r)
{
static int a=p;
switch(n)
{
case 4:a+=a*r;
case 3:a+=a*r;
case 2:a+=a*r;
case 1:a+=a*r;
}
}
(a) computes simple interest for one year (b) computes amount on compound interest for 1 to 4 years
(c) computes simple interest for four year (d) computes compound interest for 1 year
29.
a=0;
while(a<5)
printf("%d\\n",a++);
How many times does the loop occurs?
(a) infinite (b)5 (c)4 (d)6
Ans)b
30. How many times does the loop iterated ?
for(i=0;i=10;i+=2)
printf("Hi\\n");
(a)10 (b) 2 (c) 5 (d) None of these
Ans) d infinite times
31. What is incorrect among the following
A recursive function
(a) calls itself (b) is equivalent to a loop
(c) has a termination condition (d) does not have a return value at all
Ans)d
32. Which of the following go out of the loop if expn 2 becoming false
(a) while(expn 1)\{...if(expn 2)continue;} (b) while(!expn 1)\{if(expn 2)continue;...}
(c) do{..if(expn 1)continue;..}while(expn 2); (d) while(!expn 2)\{if(expn 1)continue;..\}
33. Consider the following program
main()
{
unsigned int i=10;
while(i>=0)
{
printf("%u",i)
i--;
}
}
How many times the loop will get executed
(a)10 (b)9 (c)11 (d) infinite
34.Pick out the odd one out
(a) malloc() (b) calloc() (c) free() (d) realloc()
ans) c
35.Consider the following program
main()
{
int a[5]={1,3,6,7,0};
int *b;
b=&a[2];
}
The value of b[-1] is
(a) 1 (b) 3 (c) -6 (d) none
36. # define prod(a,b)=a*b
main()
{
int x=2;
int y=3;
printf("%d",prod(x+2,y-10));
}
the output of the program is
(a) 8 (b) 6 (c) 7 (d) None
37.Consider the following program segment
int n,sum=1;
switch(n)
{
case 2:sum=sum+2;
case 3:sum*=2;
break;
default:sum=0;
}
If n=2, what is the value of sum
(a) 0 (b) 6 (c) 3 (d) None of these
38. Identify the incorrect one
1.if(c=1)
2.if(c!=3)
3.if(a 4.if(c==1)
(a) 1 only (b) 1&3 (c) 3 only (d) All of the above
39. The format specified for hexa decimal is
(a) %d (b) %o (c) %x (d) %u Ans) c
40. Find the output of the following program
main()
{
int x=5, *p;
p=&x
printf("%d",++*p);
}
(a) 5 (b) 6 (c) 0 (d) none of these
Ans ) b
41.Consider the following C code
main()
{
int i=3,x;
while(i>0)
{
x=func(i);
i--;
}
int func(int n)
{
static sum=0;
sum=sum+n;
return(sum);
}
}
The final value of x is
(a) 6 (b) 8 (c) 1 (d) 3
43. Int *a[5] refers to
(a) array of pointers (b) pointer to an array (c) pointer to a pointer (d) none of these
Ans )
44.Which of the following statements is incorrect
(a) typedef struct new
{
int n1;
char n2;
} DATA;
(b) typedef struct
{
int n3;
char *n4;
}ICE;
(c) typedef union
{
int n5;
float n6;
} UDT;
(d) #typedef union
{
int n7;
float n8;
} TUDAT;
==============================================================
.
These programs may look simple and few might have guessed the right answer for
the following.But i want to give the internal detail of working. So that you
need not worry when you find this kind of programs in life. It involves very
beautiful concepts like STACK, VARARG procedure, Function invoking .
1)
main( )
{
int i = 3;
printf ("%d %d\n", i++, ++i
);
}
ANS
: 4 4
printf
is a VARARG function, i.e printf is implemented to handle variable number of (
any number of ) arguments. Its simple template is
int
printf ( char *, ... );
Here
first argument should be an address ( Char * ) and it is must be there always.
That means you can not write printf with less than one argument, so the minimum
is one and the first one should be of an address ( Char *).
See
a simple example.
main
( )
{
char name[] = "ramakrishna" ;
printf ( name ); /* it is absolutely
OK */
}
After
char* agrument it can take any number of arguments irrespective of number % 's
in the first argument. But it has few important features that you should
concentrate.
Before
invoking PRINTF function, arguments are pushed on to the STACK in REVERSE ORDER
( Right to left).
So
printf ("%d %d\n", i++, ++i ); has two arguments. one is i ++ and
another one is ++ i . So before executing the function printf pushes ++ i onto
the stack.
i.e
( ++ 3 is 4 pushed on to the stack ) then it pushes i ++ onto the stack. ( 4++ is 4 pushed onto the stack ).
stack
is as below
4
4
after
pushing it executes the first argument. that is " %d %d "
As
soon as it find first %d it pops the stack and print an integer.
so
it prints 4, after finding the second %d it again pops the stack and print
another integer. This is how you will get 4
4.
*************
But what happens when you have two arguments and more %'s in the first
argument. IT IS WHAT THE MOST IMPORTANT *********************
IT
PRINTS SOME MEANINGFUL Value . That is ,Let me discuss something about STACK.
All the local variables you are going to declare in a program are always stored
in STACK ( It vanishes once the context is over and it is Last In First Out
(LIFO) Memory ).
While
daclaring locals all the locals are stored in STACK. For the below program it
pushes int i ( that is 3 onto the stack ) and printf arguments are pushed again
in the same way.
That
is STACK look like this.
THIRD :
4 /* i++ */
SECOND
: 4
/* ++ i */
FIRST :
3 /* Local variable */
But
because of statement i ++ , i value will increment the stack will be like this
THIRD :
4 /* i++ */
SECOND
: 4
/* ++ i */
FIRST :
5 /* Local variable */
2.)
main(
)
{
int i = 3;
printf ("%d %d %d \n", i++,
++i );
}
While printing when it find first %d it
prints the top of stack. That is 4, for second %d it prints next one 4 , for
the last %d even though printf don't have last argument it prints 5.
I
think I CONFUSED you , but NO PROBLEM once you understand this CONCEPT, you
NEED NOT SEE THIS KIND OF PROGRAMS IN YOUR LIFE AGAIN
Prints garbage
value in turbo C!!!!
main(
)
{
int i = 3;
int j = 10;
printf ("%d %d %d \n", i++,
++i );
}
stack
will be like this
FOURTH
: 4
/* ++ i */
THIRD :
4 /* i++ */
SECOND
: 10
/* Local variable j = 10 */
FIRST :
3 /* Local variable i
variables are always stored according to their order of declaration */
NOTE
: Three %d s print
4 4 10
Four %d s print 4 4 10 3
(
In some compilers it may not be answer,)
Section
1. Declarations and Initializations
1.1: How do you decide which integer type to
use?
A: If you might need large values (tens of
thousands), use long.
Otherwise, if space is very important,
use short. Otherwise,
use int.
1.4: What should the 64-bit type on a machine
that can support it?
A: C9X specifies long long.
1.7: What's the best way to declare and define
global variables?
A: The best arrangement is to place each
definition in some
relevant .c file, with an external
declaration in a header file.
1.11: What does extern mean in a function
declaration?
A: Nothing, really; the keyword extern is
optional here.
1.12: What's the auto keyword good for?
A: Nothing.
1.14: I can't seem to define a linked list node
which contains a
pointer to itself.
A: Structures in C can certainly contain
pointers to themselves;
the discussion and example in section
6.5 of K&R make this
clear.
Problems arise if an attempt is made to define (and use)
a typedef in the midst of such a
declaration; avoid this.
1.21: How do I declare an array of N pointers to
functions returning
pointers to functions returning pointers
to characters?
A: char *(*(*a[N])())();
Using a chain of typedefs, or the cdecl
program, makes these
declarations easier.
1.22: How can I declare a function that returns a
pointer to a
function of its own type?
A: You
can't quite do it directly. Use a cast,
or wrap a struct
around the pointer and return that.
1.25: My compiler is complaining about an invalid
redeclaration of a
function, but I only define it once.
A: Calling an undeclared function declares
it implicitly as
returning int.
1.25b: What's the right declaration for main()?
A: See questions 11.12a to 11.15.
1.30: What am I allowed to assume about the
initial values
of variables which are not explicitly
initialized?
A: Uninitialized variables with
"static" duration start out as 0,
as if the programmer had initialized
them. Variables with
"automatic" duration, and
dynamically-allocated memory, start
out containing garbage (with the
exception of calloc).
1.31: Why can't I initialize a local array with a
string?
A: Perhaps you have a pre-ANSI compiler.
1.31b: What's wrong with "char *p =
malloc(10);" ?
A: Function calls are not allowed in
initializers for global or
static variables.
1.32: What is the difference between char a[] =
"string"; and
char *p = "string"; ?
A: The first declares an initialized and
modifiable array; the
second declares a pointer initialized
to a not-necessarily-
modifiable constant string.
1.34: How do I initialize a pointer to a function?
A: Use something like "extern int
func(); int (*fp)() = func;" .
Section
2. Structures, Unions, and Enumerations
2.1: What's the difference between struct x1 {
... }; and
typedef struct { ... } x2; ?
A: The first structure is named by a tag,
the second by a typedef
name.
2.2: Why doesn't "struct x { ... }; x
thestruct;" work?
A: C is not C++.
2.3: Can a structure contain a pointer to
itself?
A: See question 1.14.
2.4: What's the best way of implementing opaque
(abstract) data types
in C?
A: One good way is to use structure pointers
which point to
structure types which are not publicly
defined.
2.6: I came across some code that declared a
structure with the last
member an array of one element, and
then did some tricky
allocation to make it act like the
array had several elements.
Is this legal or portable?
A: An official interpretation has deemed
that it is not strictly
conforming with the C Standard.
2.7: I heard that structures could be assigned
to variables and
passed to and from functions, but
K&R1 says not.
A: These operations are supported by all
modern compilers.
2.8: Is there a way to compare structures
automatically?
A: No.
2.10: Can I pass constant values to functions
which accept structure
arguments?
A: Not yet.
As of this writing, C has no way of generating
anonymous structure values.
2.11: How can I read/write structures from/to data
files?
A: It is relatively straightforward to use
fread and fwrite.
2.12: How can I turn off structure padding?
A: There is no standard method.
2.13: Why does sizeof report a larger size than I
expect for a
structure type?
A: The alignment of arrays of structures
must be preserved.
2.14: How can I determine the byte offset of a
field within a
structure?
A: ANSI C defines the offsetof() macro,
which should be used if
available.
2.15: How can I access structure fields by name at
run time?
A: Build a table of names and offsets, using
the offsetof() macro.
2.18: I have a program which works correctly, but
dumps core after it
finishes. Why?
A: Check to see if a structure type
declaration just before main()
is missing its trailing semicolon,
causing main() to be declared
as returning a structure. See also questions 10.9 and 16.4.
2.20: Can I initialize unions?
A: The current C Standard allows an
initializer for the first-named
member.
2.22: What is the difference between an
enumeration and a set of
preprocessor #defines?
A: At the present time, there is little
difference. The C Standard
states that enumerations are compatible
with integral types.
2.24: Is there an easy way to print enumeration
values symbolically?
A: No.
Section
3. Expressions
3.1: Why doesn't the code "a[i] =
i++;" work?
A: The variable i is both referenced and
modified in the same
expression.
3.2: Under my compiler, the code "int i = 7;
printf("%d\n", i++ *
i++);" prints 49. Regardless of the
order
of evaluation, shouldn't it print 56?
A: The operations implied by the
postincrement and postdecrement
operators ++ and -- are performed at
some time after the
operand's former values are yielded and
before the end of the
expression, but not necessarily
immediately after, or before
other parts of the expression are
evaluated.
3.3: What should the code "int i = 3; i =
i++;" do?
A: The
expression is undefined.
3.3b: Here's a slick expression: "a ^= b ^= a
^= b". It swaps a and b
without using a temporary.
A: Not portably; its behavior is undefined.
3.4: Don't precedence and parentheses dictate
order of evaluation?
3.3b: Here's a slick expression: "a ^= b ^= a
^= b". It swaps a and b
without using a temporary.
A: Not portably; its behavior is undefined.
3.4: Don't precedence and parentheses dictate
order of evaluation?
A: Operator precedence and explicit
parentheses impose only a
partial ordering on the evaluation of
an expression, which does
not generally include the order of side
effects.
3.5: But what about the && and ||
operators?
A: There is a special exception for those
operators: left-to-right
evaluation is guaranteed.
3.8: What's a "sequence point"?
A: A point (at the end of a full expression,
or at the ||, &&, ?:,
or comma operators, or just before a
function call) at which all
side effects are guaranteed to be
complete.
3.9: So given a[i] = i++; we don't know which
cell of a[] gets
written to, but i does get incremented
by one, right?
A: *No*.
Once an expression or program becomes undefined, *all*
aspects of it become undefined.
3.12: If I'm not using the value of the
expression, should I use i++
or ++i to increment a variable?
A: Since the two forms differ only in the
value yielded, they are
entirely equivalent when only their
side effect is needed.
3.14: Why doesn't the code "int a = 1000, b =
1000;
long int c = a * b;" work?
A: You must manually cast one of the
operands to (long).
3.16: Can I use ?: on the left-hand side of an
assignment expression?
A: No.
Section
4. Pointers
4.2: What's wrong with "char *p; *p =
malloc(10);"?
A: The pointer you declared is p, not *p.
4.3: Does *p++ increment p, or what it points
to?
A: *p++ increments p. To increment the value pointed to by p, use
(*p)++ .
4.5: I want to use a char * pointer to step over
some ints. Why
doesn't "((int *)p)++;" work?
A: In C, a cast operator is a conversion
operator, and by
definition it yields an rvalue, which
cannot be assigned to, or
incremented with ++.
4.8: I have a function which accepts, and is
supposed to initialize,
a pointer, but the pointer in the
caller remains unchanged.
A: The called function probably altered only
the passed copy of the
pointer.
4.9: Can I use a void ** pointer as a parameter
so that a function
can accept a generic pointer by
reference?
A: Not portably.
4.10: I have a function which accepts a pointer to
an int. How can I
pass a constant like 5 to it?
A: You will have to declare a temporary
variable.
4.11: Does C even have "pass by
reference"?
A: Not really, though it can be simulated.
4.12: I've seen different methods used for calling
functions via
A: The extra parentheses and explicit * are
now>
Transfer
interrupted!
older
implementations require them.
Section
5. Null Pointers
5.1: What is this infamous null pointer, anyway?
A: For each pointer type, there is a special
value -- the "null
pointer" -- which is
distinguishable from all other pointer
values and which is not the address of
any object or function.
5.2: How do I get a null pointer in my programs?
A: A
constant 0 in a pointer context is converted into a null
pointer at compile time. A "pointer context" is an
initialization, assignment, or
comparison with one side a
variable or expression of pointer type,
and (in ANSI standard C)
a function argument which has a
prototype in scope declaring a
certain parameter as being of pointer
type. In other contexts
(function arguments without prototypes,
or in the variable part
of variadic function calls) a constant
0 with an appropriate
explicit cast is required.
5.3: Is the abbreviated pointer comparison
"if(p)" to test for non-
null pointers valid?
A: Yes.
The construction "if(p)" works, regardless of the internal
representation of null pointers,
because the compiler
essentially rewrites it as "if(p
!= 0)" and goes on to convert 0
into the correct null pointer.
5.4: What is NULL and how is it #defined?
A: NULL is simply a preprocessor macro,
#defined as 0 (or
((void *)0)), which is used (as a
stylistic convention, in
preference to unadorned 0's) to
generate null pointers.
5.5: How should NULL be defined on a machine
which uses a nonzero bit
pattern as the internal representation
of a null pointer?
A: The same as on any other machine: as
0. (The compiler makes the
translation, upon seeing a 0, not the
preprocessor; see also
question 5.4.)
5.6: If NULL were defined as "((char
*)0)," wouldn't that make
function calls which pass an uncast
NULL work?
A: Not in general. The complication is that there are machines
which use different internal
representations for pointers to
different types of data. A cast is still required to tell the
compiler which kind of null pointer is
required, since it may be
different from (char *)0.
5.9: If NULL and 0 are equivalent as null
pointer constants, which
should I use?
A: Either; the distinction is entirely
stylistic.
5.10: But wouldn't it be better to use NULL, in
case the value of NULL
changes?
A: No.
NULL is a constant zero, so a constant zero is equally
sufficient.
5.12: I use the preprocessor macro "#define
Nullptr(type) (type *)0"
to help me build null pointers of the
correct type.
A: This trick, though valid, does not buy
much.
5.13: This is strange. NULL is guaranteed to be 0, but the null
pointer is not?
A: A "null pointer" is a language
concept whose particular internal
value does not matter. A null pointer is requested in source
code with the character
"0". "NULL" is a
preprocessor macro,
which is always #defined as 0 (or
((void *)0)).
5.14: Why is there so much confusion surrounding
null pointers?
A: The fact that null pointers are
represented both in source code,
and internally to most machines, as
zero invites unwarranted
assumptions. The use of a preprocessor macro (NULL) may
seem to
suggest that the value could change
some day, or on some weird
machine.
5.15: I'm confused. I just can't understand all this null pointer
stuff.
A: A simple rule is, "Always use `0' or
`NULL' for null pointers,
and always cast them when they are used
as arguments in function
calls."
5.16: Given all the confusion surrounding null
pointers, wouldn't it
be easier simply to require them to be
represented internally by
zeroes?
A: Such a requirement would accomplish
little.
5.17: Seriously, have any actual machines really
used nonzero null
pointers?
A: Machines manufactured by Prime,
Honeywell-Bull, and CDC, as well
as Symbolics Lisp Machines, have done
so.
5.20: What does a run-time "null pointer
assignment" error mean?
A: It means that you've written, via a null
pointer, to an invalid
location. (See also question 16.8.)
Section
6. Arrays and Pointers
6.1: I had the definition char a[6] in one
source file, and in
another I declared extern char *a. Why didn't it work?
A: The declaration extern char *a simply
does not match the actual
definition. Use extern char a[].
6.2: But I heard that char a[] was identical to
char *a.
A: Not at all. Arrays are not pointers. A reference like x[3]
generates different code depending on
whether x is an array or a
pointer.
6.3: So what is meant by the "equivalence
of pointers and arrays" in
C?
A: An lvalue of type array-of-T which
appears in an expression
decays into a pointer to its first
element; the type of the
resultant pointer is pointer-to-T. So for an array a and
pointer p, you can say "p =
a;" and then p[3] and a[3] will
access the same element.
6.4: Why are array and pointer declarations
interchangeable as
function formal parameters?
A: It's supposed to be a convenience.
6.7: How can an array be an lvalue, if you can't
assign to it?
A: An array is not a "modifiable
lvalue."
6.8: What is the real difference between arrays
and pointers?
A: Arrays automatically allocate space which
is fixed in size and
location; pointers are dynamic.
6.9: Someone explained to me that arrays were
really just constant
pointers.
A: An array name is "constant" in
that it cannot be assigned to,
but an array is *not* a pointer.
6.11: I came across some "joke" code
containing the "expression"
5["abcdef"] . How can this be legal C?
A: Yes, array subscripting is commutative in
C. The array
subscripting operation a[e] is defined
as being identical to
*((a)+(e)).
6.12: What's the difference between array and
&array?
A: The type.
6.13: How do I declare a pointer to an array?
A: Usually, you don't want to. Consider using a pointer to one of
the array's elements instead.
6.14: How can I set an array's size at run time?
A: It's straightforward to use malloc() and
a pointer.
6.15: How can I declare local arrays of a size
matching a passed-in
array?
A: Until recently, you couldn't; array
dimensions had to be compile-
time constants. C9X will fix this.
6.16: How can I dynamically allocate a
multidimensional array?
A: The traditional solution is to allocate
an array of pointers,
and then initialize each pointer to a
dynamically-allocated
"row." See the full
list for code samples.
6.17: Can I simulate a non-0-based array with a
pointer?
A: Not if the pointer points outside of the
block of memory it is
intended to access.
6.18: My compiler complained when I passed a
two-dimensional array to
a function expecting a pointer to a
pointer.
A: The rule by which arrays decay into
pointers is not applied
recursively. An array of arrays (i.e. a two-dimensional
array
in C) decays into a pointer to an
array, not a pointer to a
pointer.
6.19: How do I write functions which accept
two-dimensional arrays
when the width is not known at compile
time?
A: It's not always particularly easy.
6.20: How can I use statically- and dynamically-allocated
multidimensional arrays interchangeably
when passing them to
functions?
A: There is no single perfect method, but
see the full list for
some ideas.
6.21: Why doesn't sizeof properly report the size
of an array which is
a parameter to a function?
A: The sizeof operator reports the size of
the pointer parameter
which the function actually receives.
Section
7. Memory Allocation
7.1: Why doesn't the code "char *answer;
gets(answer);" work?
A: The pointer variable answer has not been
set to point to any
valid storage. The simplest way to correct this fragment is
to
use a local array, instead of a
pointer.
7.2: I can't get strcat() to work. I tried "char *s3 =
strcat(s1, s2);" but I got strange
results.
A: Again, the main problem here is that
space for the concatenated
result is not properly allocated.
7.3: But the man page for strcat() says that it
takes two char *'s as
arguments. How am I supposed to know to allocate things?
A: In general, when using pointers you
*always* have to consider
memory allocation, if only to make sure
that the compiler is
doing it for you.
7.3b: I just tried the code "char *p;
strcpy(p, "abc");" and it
worked.
Why didn't it crash?
A: You got "lucky".
7.3c: How much memory does a pointer variable
allocate?
A: Only enough memory to hold the pointer
itself, not any memory
for the pointer to point to.
7.5a: I have a function that is supposed to return
a string, but when
it returns to its caller, the returned
string is garbage.
A: Make sure that the pointed-to memory is
properly (i.e. not
locally) allocated.
7.5b: So what's the right way to return a string?
A: Return a pointer to a
statically-allocated buffer, a buffer
passed in by the caller, or memory
obtained with malloc().
7.6: Why am I getting "warning: assignment
of pointer from integer
lacks a cast" for calls to
malloc()?
A: Have you #included ?
7.7: Why does some code carefully cast the
values returned by malloc
to the pointer type being allocated?
A: Before ANSI/ISO C, these casts were
required to silence certain
warnings.
7.8: Why does so much code leave out the
multiplication by
sizeof(char) when allocating strings?
A: Because sizeof(char) is, by definition,
exactly 1.
7.14: I've heard that some operating systems don't
actually allocate
malloc'ed memory until the program
tries to use it. Is this
legal?
A: It's hard to say.
7.16: I'm allocating a large array for some
numeric work, but malloc()
is acting strangely.
A: Make sure the number you're trying to
pass to malloc() isn't
bigger than a size_t can hold.
7.17: I've got 8 meg of memory in my PC. Why can I only seem to
malloc 640K or so?
A: Under the segmented architecture of PC
compatibles, it can be
difficult to use more than 640K with
any degree of transparency.
See also question 19.23.
7.19: My program is crashing, apparently somewhere
down inside malloc.
A: Make sure you aren't using more memory
than you malloc'ed,
especially for strings (which need strlen(str)
+ 1 bytes).
7.20: You can't use dynamically-allocated memory
after you free it,
can you?
A: No.
Some early documentation implied otherwise, but the claim
is no longer valid.
7.21: Why
isn't a pointer null after calling free()?
A: C's pass-by-value semantics mean that
called functions can never
permanently change the values of their
arguments.
7.22: When I call malloc() to allocate memory for
a local pointer, do
I
have to explicitly free() it?
A: Yes.
7.23: When I free a dynamically-allocated
structure containing
pointers, do I also have to free each
subsidiary pointer?
A: Yes.
7.24: Must I free allocated memory before the
program exits?
A: You shouldn't have to.
7.25: Why doesn't my program's memory usage go
down when I free
memory?
A: Most implementations of malloc/free do
not return freed memory
to the operating system.
7.26: How does free() know how many bytes to free?
A: The malloc/free implementation remembers
the size of each block
as it is allocated.
7.27: So can I query the malloc package to find
out how big an
allocated block is?
A: Not portably.
7.30: Is it legal to pass a null pointer as the
first argument to
realloc()?
A: ANSI C sanctions this usage, although
several earlier
implementations do not support it.
7.31: What's the difference between calloc() and
malloc()?
A: calloc() takes two arguments, and
initializes the allocated
memory to all-bits-0.
7.32: What is alloca() and why is its use
discouraged?
A: alloca() allocates memory which is
automatically freed when the
function which called alloca()
returns. alloca() cannot be
written portably, is difficult to
implement on machines without
a stack, and fails under certain
conditions if implemented
simply.
Section
8. Characters and Strings
8.1: Why doesn't "strcat(string,
'!');" work?
A: strcat() concatenates *strings*, not
characters.
8.2: Why won't the test if(string ==
"value") correctly compare
string against the value?
A: It's comparing pointers. To compare two strings, use strcmp().
8.3: Why can't I assign strings to character
arrays?
A: Strings are arrays, and you can't assign
arrays directly. Use
strcpy() instead.
8.6: How can I get the numeric (character set)
value corresponding to
a character?
A: In C, if you have the character, you have
its value.
8.9: Why is sizeof('a') not 1?
A: Character constants in C are of type int.
Section
9. Boolean Expressions and Variables
9.1: What is the right type to use for Boolean
values in C?
A: There's no one right answer; see the full list
for some
discussion.
9.2: What if a built-in logical or relational
operator "returns"
something other than 1?
A: When a Boolean value is generated by a
built-in operator, it is
guaranteed to be 1 or 0. (This is *not* true for some library
routines such as isalpha.)
9.3: Is if(p), where p is a pointer, valid?
A: Yes.
See question 5.3.
Section
10. C Preprocessor
10.2: I've got some cute preprocessor macros that
let me write C code
that looks more like Pascal. What do y'all think?
A: Bleah.
10.3: How can I write a generic macro to swap two
values?
A: There is no good answer to this
question. The best all-around
solution is probably to forget about
using a macro.
10.4: What's the best way to write a
multi-statement macro?
A: #define Func() do {stmt1; stmt2; ... }
while(0) /* (no trailing ;) */
10.6: What are .h files and what should I put in
them?
A: Header files (also called ".h
files") should generally contain
common declarations and macro,
structure, and typedef
definitions, but not variable or
function definitions.
10.7: Is it acceptable for one header file to
#include another?
A:
It's a question of style, and thus
receives considerable debate.
10.8a: What's the difference between #include
<> and #include "" ?
A: Roughly speaking, the <> syntax is
for Standard headers and ""
is for project headers.
10.8b: What are the complete rules for header file
searching?
A: The exact behavior is
implementation-defined; see the full list
for some discussion.
10.9: I'm getting strange syntax errors on the
very first declaration
in a file, but it looks fine.
A: Perhaps there's a missing semicolon at
the end of the last
declaration in the last header file
you're #including.
10.10b:
I'm #including the header file for a function, but the linker
keeps saying it's undefined.
A: See question 13.25.
10.11: Where can I get a copy of a missing header
file?
A: Contact your vendor, or see question
18.16 or the full list.
10.12: How can I construct preprocessor #if
expressions which compare
strings?
A: You can't do it directly; try #defining
several manifest
constants and implementing conditionals
on those.
10.13: Does the sizeof operator work in preprocessor
#if directives?
A: No.
10.14: Can I use an #ifdef in a #define line, to
define something two
different ways?
A: No.
10.15: Is there anything like an #ifdef for
typedefs?
A: Unfortunately, no.
10.16: How can I use a preprocessor #if expression
to detect
endianness?
A: You probably can't.
10.18: How can I preprocess some code to remove
selected conditional
compilations, without preprocessing
everything?
A: Look for a program called unifdef,
rmifdef, or scpp.
10.19: How can I list all of the predefined
identifiers?
A: If the compiler documentation is
unhelpful, try extracting
printable strings from the compiler or
preprocessor executable.
10.20: I have some old code that tries to construct
identifiers with a
macro like "#define Paste(a, b)
a/**/b", but it doesn't work any
more.
A: Try the ANSI token-pasting operator ##.
10.22: What does the message "warning: macro
replacement within a
string literal" mean?
A: See question 11.18.
10.23-4:
I'm having trouble using macro arguments inside string
literals, using the `#' operator.
A: See questions 11.17 and 11.18.
10.25: I've got this tricky preprocessing I want to
do and I can't
figure out a way to do it.
A: Consider writing your own little
special-purpose preprocessing
tool, instead.
10.26: How can I write a macro which takes a
variable number of
arguments?
A: Here is one popular trick. Note that the parentheses around
printf's argument list are in the macro
call, not the
definition.
#define DEBUG(args)
(printf("DEBUG: "), printf args)
if(n != 0) DEBUG(("n is
%d\n", n));
Section
11. ANSI/ISO Standard C
11.1: What is the "ANSI C Standard?"
A: In 1983, the American National Standards
Institute (ANSI)
commissioned a committee to standardize
the C language. Their
work was ratified as ANS X3.159-1989,
and has since been adopted
as ISO/IEC 9899:1990, and later
amended.
11.2: How can I get a copy of the Standard?
A: Copies are available from ANSI in New
York, or from Global
Engineering Documents in Englewood, CO,
or from any national
standards body, or from ISO in Geneva,
or republished within one
or more books. See the unabridged list for details.
11.2b: Where can I get information about updates to
the Standard?
A: See the full list for pointers.
11.3: My ANSI compiler is complaining about
prototype mismatches for
parameters declared float.
A: You have mixed the new-style prototype
declaration
"extern int func(float);"
with the old-style definition
"int func(x) float x;". "Narrow" types are treated
differently
according to which syntax is used. This problem can be fixed by
avoiding narrow types, or by using
either new-style (prototype)
or old-style syntax consistently.
11.4: Can you mix old-style and new-style function
syntax?
A: Doing so is currently legal, for most
argument types
(see question 11.3).
11.5: Why does the declaration "extern int
f(struct x *p);" give me a
warning message?
A: A structure declared (or even mentioned)
for the first time
within a prototype cannot be compatible
with other structures
declared in the same source file.
11.8: Why can't I use const values in initializers
and array
dimensions?
A: The value of a const-qualified object is
*not* a constant
expression in the full sense of the
term.
11.9: What's the difference between "const
char *p" and
"char * const p"?
A: The former declares a pointer to a
constant character; the
latter declares a constant pointer to a
character.
11.10: Why can't I pass a char ** to a function
which expects a
const char **?
A: The rule which permits slight mismatches
in qualified pointer
assignments is not applied recursively.
11.12a:
What's the correct declaration of main()?
A: int main(int argc, char *argv[]) .
11.12b:
Can I declare main() as void, to shut off these annoying "main
returns no value" messages?
A: No.
11.13: But what about main's third argument, envp?
A: It's a non-standard (though common)
extension.
11.14: I believe that declaring void main() can't
fail, since I'm
calling exit() instead of returning.
A: It doesn't matter whether main() returns
or not, the problem is
that its caller may not even be able to
*call* it correctly.
11.15: The book I've been using always uses void
main().
A: It's wrong.
11.16: Is exit(status) truly equivalent to returning
the same status
from main()?
A: Yes and no. (See the full list for details.)
11.17: How do I get the ANSI "stringizing"
preprocessing operator `#'
to stringize the macro's value instead of
its name?
A: You can use a two-step #definition to
force a macro to be
expanded as well as stringized.
11.18: What does the message "warning: macro
replacement within a
string literal" mean?
A: Some pre-ANSI compilers/preprocessors
expanded macro parameters
even inside string literals and
character constants.
11.19: I'm getting strange syntax errors inside
lines I've #ifdeffed
out.
A: Under ANSI C, #ifdeffed-out text must
still consist of "valid
preprocessing tokens." This means that there must be no
newlines inside quotes, and no
unterminated comments or quotes
(i.e. no single apostrophes).
11.20: What are #pragmas ?
A: The #pragma directive provides a single,
well-defined "escape
hatch" which can be used for
extensions.
11.21: What does "#pragma once" mean?
A: It is an extension implemented by some
preprocessors to help
make header files idempotent.
11.22: Is char a[3] = "abc"; legal?
A: Yes, in ANSI C.
11.24: Why can't I perform arithmetic on a void *
pointer?
A: The compiler doesn't know the size of the
pointed-to objects.
11.25: What's the difference between memcpy() and
memmove()?
A: memmove() offers guaranteed behavior if
the source and
destination arguments overlap.
11.26: What should malloc(0) do?
A: The behavior is implementation-defined.
11.27: Why does the ANSI Standard not guarantee more
than six case-
insensitive characters of external
identifier significance?
A: The problem is older linkers which cannot
be forced (by mere
words in a Standard) to upgrade.
11.29: My compiler is rejecting the simplest
possible test programs,
with all kinds of syntax errors.
A: Perhaps it is a pre-ANSI compiler.
11.30: Why are some ANSI/ISO Standard library
functions showing up as
undefined, even though I've got an ANSI
compiler?
A: Perhaps you don't have ANSI-compatible
headers and libraries.
11.31: Does anyone have a tool for converting
old-style C programs to
ANSI C, or for automatically generating
prototypes?
A: See the full list for details.
11.32: Why won't frobozz-cc, which claims to be ANSI
compliant, accept
this code?
A: Are you sure that the code being rejected
doesn't rely on some
non-Standard extension?
11.33: What's the difference between
implementation-defined,
unspecified, and undefined behavior?
A: If
you're writing portable code, ignore the distinctions.
Otherwise, see the full list.
11.34: I'm appalled that the ANSI Standard leaves so
many issues
undefined.
A: In most of these cases, the Standard is
simply codifying
existing practice.
11.35: I just tried some allegedly-undefined code on
an ANSI-conforming
compiler, and got the results I
expected.
A: A compiler may do anything it likes when
faced with undefined
behavior, including doing what you
expect.
Section
12. Stdio
12.1: What's wrong with the code "char c;
while((c = getchar()) !=
EOF) ..."?
A: The variable to hold getchar's return
value must be an int.
12.2: Why won't the code "while(!feof(infp))
{
fgets(buf, MAXLINE, infp); fputs(buf,
outfp); }" work?
A: EOF is only indicated *after* an input
routine fails.
12.4: My program's prompts and intermediate output
don't always show
up on the screen.
A: It's best to use an explicit fflush(stdout)
whenever output
should definitely be visible.
12.5: How can I read one character at a time,
without waiting for the
RETURN key?
A: See question 19.1.
12.6: How can I print a '%' character with printf?
A: "%%".
12.9: How can printf() use %f for type double, if
scanf() requires
%lf?
A: C's "default argument
promotions" mean that values of type float
are promoted to double.
12.9b: What printf format should I use for a typedef
when I don't know
the underlying type?
A: Use a cast to convert the value to a
known type, then use the
printf format matching that type.
12.10: How can I implement a variable field width
with printf?
A: Use printf("%*d", width, x).
12.11: How can I print numbers with commas
separating the thousands?
A: There is no standard routine (but see
).
12.12: Why doesn't the call scanf("%d", i)
work?
A: The arguments you pass to scanf() must
always be pointers.
12.13: Why doesn't the code "double d;
scanf("%f", &d);" work?
A: Unlike printf(), scanf() uses %lf for
double, and %f for float.
12.15: How can I specify a variable width in a
scanf() format string?
A: You can't.
12.17: When I read numbers from the keyboard with
scanf "%d\n", it
seems to hang until I type one extra
line of input.
A: Try using "%d" instead of
"%d\n".
12.18: I'm reading a number with scanf %d and then a
string with
gets(), but the compiler seems to be
skipping the call to
gets()!
A: scanf() and gets() do not work well
together.
12.19: I'm re-prompting the user if scanf() fails,
but sometimes it
seems to go into an infinite loop.
A: scanf() tends to "jam" on bad
input since it does not discard
it.
12.20: Why does everyone say not to use
scanf()? What should I use
instead?
A: scanf() has a number of problems. Usually, it's easier to read
entire lines and then interpret them.
12.21: How can I tell how much destination buffer
space I'll need for
an arbitrary sprintf call? How can I avoid overflowing the
destination buffer with sprintf()?
A: Use the new snprintf() function, if you
can.
12.23: Why does everyone say not to use gets()?
A: It cannot be prevented from overflowing
the input buffer.
12.24: Why does errno contain ENOTTY after a call to
printf()?
A: Don't worry about it. It is only meaningful for a program to
inspect the contents of errno after an
error has been reported.
12.25: What's the difference between fgetpos/fsetpos
and ftell/fseek?
A: fgetpos() and fsetpos() use a special
typedef which may allow
them to work with larger files than
ftell() and fseek().
12.26: Will fflush(stdin) flush unread characters
from the standard
input stream?
A: No.
12.30: I'm trying to update a file in place, by
using fopen mode "r+",
but it's not working.
A: Be sure to call fseek between reading and
writing.
12.33: How can I redirect stdin or stdout from
within a program?
A: Use freopen().
12.34: Once I've used freopen(), how can I get the
original stream
back?
A: There isn't a good way. Try avoiding freopen.
12.36b:
How can I arrange to have output go two places at once?
A: You could write your own printf variant
which printed everything
twice.
See question 15.5.
12.38: How can I read a binary data file properly?
A: Be sure to specify "rb" mode
when calling fopen().
Section
13. Library Functions
13.1: How can I convert numbers to strings?
A: Just use sprintf().
13.2: Why does strncpy() not always write a '\0'?
A: For mildly-interesting historical
reasons.
13.5: Why do some versions of toupper() act
strangely if given an
upper-case letter?
A: Older versions of toupper() and tolower()
did not always work as
expected in this regard.
13.6: How can I split up a string into
whitespace-separated fields?
A: Try strtok().
13.7: I need some code to do regular expression
and wildcard matching.
A: regexp libraries abound; see the full
list for details.
13.8: I'm trying to sort an array of strings with
qsort(), using
strcmp() as the comparison function,
but it's not working.
A: You'll have to write a "helper"
comparison function which takes
two generic pointer arguments, converts
them to char **, and
dereferences them, yielding char *'s
which can be usefully
compared.
13.9: Now I'm trying to sort an array of
structures, but the compiler
is complaining that the function is of
the wrong type for
qsort().
A: The comparison function must be declared
as accepting "generic
pointers" (const void *) which it
then converts to structure
pointers.
13.10: How can I sort a linked list?
A: Algorithms like insertion sort and merge
sort work well, or you
can keep the list in order as you build
it.
13.11: How can I sort more data than will fit in
memory?
A: You want an "external sort";
see the full list for details.
13.12: How can I get the time of day in a C program?
A: Just use the time(), ctime(), localtime()
and/or strftime()
functions.
13.13: How can I convert a struct tm or a string
into a time_t?
A: The ANSI mktime() function converts a
struct tm to a time_t. No
standard routine exists to parse
strings.
13.14: How can I perform calendar manipulations?
A: The ANSI/ISO Standard C mktime() and
difftime() functions
provide some support for both problems.
13.14b:
Does C have any Year 2000 problems?
A: No, although poorly-written C programs
do. Make sure you know
that tm_year holds the value of the
year minus 1900.
13.15: I need a random number generator.
A: The Standard C library has one: rand().
13.16: How can I get random integers in a certain
range?
A: One method is something like
(int)((double)rand() /
((double)RAND_MAX + 1) * N)
13.17: Each time I run my program, I get the same
sequence of numbers
back from rand().
A: You can call srand() to seed the
pseudo-random number generator
with a truly random initial value.
13.18: I need a random true/false value, so I'm just
taking rand() % 2,
but it's alternating 0, 1, 0, 1, 0...
A: Try using the higher-order bits: see
question 13.16.
13.20: How can I generate random numbers with a
normal or Gaussian
distribution?
A: See the longer versions of this list for
ideas.
13.24: I'm trying to port this old program. Why do I get "undefined
external" errors for some library
functions?
A: Some semistandard functions have been
renamed or replaced over
the years; see the full list for
details.
13.25: I get errors due to library functions being
undefined even
though I #include the right header
files.
A: You may have to explicitly ask for the
correct libraries to be
searched.
13.26: I'm still getting errors due to library
functions being
undefined, even though I'm requesting
the right libraries.
A: Library search order is significant;
usually, you must search
the libraries last.
13.28: What does it mean when the linker says that
_end is undefined?
A: You generally get that message only when
other symbols are
undefined, too.
Section
14. Floating Point
14.1: When I set a float variable to 3.1, why is
printf printing it as
3.0999999?
A: Most computers use base 2 for
floating-point numbers, and many
fractions (including 0.1 decimal) are
not exactly representable
in base 2.
14.2: Why is sqrt(144.) giving me crazy numbers?
A: Make sure that you have #included
declared other functions returning
double.
14.3: I keep getting "undefined: sin"
compilation errors.
A: Make sure you're actually linking with
the math library.
14.4: My floating-point calculations are acting
strangely and giving
me different answers on different
machines.
A: First, see question 14.2 above. If the problem isn't that
simple, see the full list for a brief
explanation, or any good
programming book for a better one.
14.5: What's a good way to check for "close
enough" floating-point
equality?
A: The best way is to use an accuracy
threshold which is relative
to the magnitude of the numbers being
compared.
14.6: How do I round numbers?
A: For positive numbers, try (int)(x + 0.5)
.
14.7: Where is C's exponentiation operator?
A: Try using the pow() function.
14.8: The predefined constant M_PI seems to be
missing from
A: That constant is not standard.
14.9: How do I test for IEEE NaN and other special
values?
A: There is not yet a portable way, but see
the full list for
ideas.
14.11: What's a good way to implement complex
numbers in C?
A: It is straightforward to define a simple
structure and some
arithmetic functions to manipulate them.
14.12: I'm looking for some mathematical library
code.
A: See Ajay Shah's index of free numerical
software at
ftp://ftp.math.psu.edu/pub/FAQ/numcomp-free-c .
14.13: I'm having trouble with a Turbo C program
which crashes and says
something like "floating point
formats not linked."
A: You may have to insert a dummy call to a
floating-point library
function to force loading of
floating-point support.
Section
15. Variable-Length Argument Lists
15.1: I heard that you have to #include
before calling
printf(). Why?
A: So that a proper prototype for printf()
will be in scope.
15.2: How can %f be used for both float and double
arguments in
printf()?
A: In variable-length argument lists, types
char and short int are
promoted to int, and float is promoted
to double.
15.3: Why don't function prototypes guard against
mismatches in
printf's arguments?
A: Function prototypes do not provide any
information about the
number and types of variable arguments.
15.4: How can I write a function that takes a
variable number of
arguments?
A: Use the header.
15.5: How can I write a function that takes a
format string and a
variable number of arguments, like
printf(), and passes them to
printf() to do most of the work?
A: Use vprintf(), vfprintf(), or vsprintf().
15.6: How can I write a function analogous to
scanf(), that calls
scanf() to do most of the work?
A: C9X will support vscanf().
15.7: I have a pre-ANSI compiler, without
. What can I do?
A: There's an older header,
, which offers about the
same functionality.
15.8: How can I discover how many arguments a
function was actually
called with?
A: Any function which takes a variable
number of arguments must be
able to determine *from the arguments'
values* how many of them
there are.
15.9: My compiler isn't letting me declare a
function that accepts
*only* variable arguments.
A: Standard C requires at least one fixed
argument.
15.10: Why isn't "va_arg(argp, float)"
working?
A: Because the "default argument promotions"
apply in variable-
length argument lists, you should
always use
va_arg(argp, double).
15.11: I can't get va_arg() to pull in an argument
of type pointer-to-
function.
A: Use a typedef.
15.12: How can I write a function which takes a
variable number of
arguments and passes them to some other
function ?
A: In general, you cannot.
15.13: How can I call a function with an argument
list built up at run
time?
A: You can't.
Section
16. Strange Problems
16.1b: I'm getting baffling syntax errors which make
no sense at all,
and it seems like large chunks of my
program aren't being
compiled.
A: Check for unclosed comments or mismatched
preprocessing
directives.
16.1c: Why isn't my procedure call working?
A: Function calls always require
parenthesized argument lists.
16.3: This program crashes before it even runs!
A: Look for very large, local arrays.
(See also questions 11.12b, 16.4, 16.5,
and 18.4.)
16.4: I have a program that seems to run
correctly, but then crashes
as it's exiting.
A: See the full list for ideas.
16.5: This program runs perfectly on one machine,
but I get weird
results on another.
A: See the full list for a brief list of
possibilities.
16.6: Why does the code "char *p =
"hello, world!"; p[0] = 'H';"
crash?
A: String literals are not modifiable,
except (in effect) when they
are used as array initializers.
16.8: What does "Segmentation violation"
mean?
A: It generally means that your program
tried to access memory it
shouldn't have, invariably as a result
of stack corruption or
improper pointer use.
Section
17. Style
17.1: What's the best style for code layout in C?
A: There is no one "best style,"
but see the full list for a few
suggestions.
17.3: Is the code "if(!strcmp(s1, s2))"
good style?
A: Not particularly.
17.4: Why do some people write if(0 == x) instead
of if(x == 0)?
A: It's a trick to guard against the common
error of writing
if(x = 0) .
17.5: I came across some code that puts a (void)
cast before each call
to printf(). Why?
A: To suppress warnings about otherwise discarded
return values.
17.8: What is "Hungarian Notation"?
A: It's a naming convention which encodes
information about a
variable's type in its name.
17.9: Where can I get the "Indian Hill Style
Guide" and other coding
standards?
A: See the unabridged list.
17.10: Some people say that goto's are evil and that
I should never use
them.
Isn't that a bit extreme?
A: Yes.
Absolute rules are an imperfect approach to good
programming style.
Section
18. Tools and Resources
18.1: I'm looking for C development tools
(cross-reference generators,
code beautifiers, etc.).
A: See the full list for a few names.
18.2: How can I track down these pesky malloc
problems?
A: See the full list for a list of tools.
18.3: What's a free or cheap C compiler I can use?
A: See the full list for a brief catalog.
18.4: I just typed in this program, and it's
acting strangely. Can
you see anything wrong with it?
A: See if you can run lint first.
18.5: How can I shut off the "warning:
possible pointer alignment
problem" message which lint gives
me for each call to malloc()?
A: It may be easier simply to ignore the
message, perhaps in an
automated way with grep -v.
18.7: Where can I get an ANSI-compatible lint?
A: See the unabridged list for two
commercial products.
18.8: Don't ANSI function prototypes render lint
obsolete?
A: No.
A good compiler may match most of lint's diagnostics; few
provide all.
18.9: Are there any C tutorials or other resources
on the net?
A: There are several of them.
18.10: What's a good book for learning C?
A: There are far too many books on C to list
here; the full list
contains a few pointers.
18.13: Where can I find the sources of the standard
C libraries?
A: Several possibilites are listed in the
full list.
18.13b:
Is there an on-line C reference manual?
A: Two possibilities are
http://www.cs.man.ac.uk/standard_c/_index.html
and
http://www.dinkumware.com/htm_cl/index.html .
18.13c:
Where can I get a copy of the ANSI/ISO C Standard?
A: See question 11.2.
18.14: I need code to parse and evaluate
expressions.
A: Several available packages are mentioned
in the full list.
18.15: Where can I get a BNF or YACC grammar for C?
A: See the ANSI Standard, or the unabridged
list.
18.15b:
Does anyone have a C compiler test suite I can use?
A: See the full list for several sources.
18.15c:
Where are some collections of useful code fragments and
examples?
A: See the full list for a few sources.
18.15d:
I need code for performing multiple precision arithmetic.
A: See the full list for a few ideas.
18.16: Where and how can I get copies of all these
freely distributable
programs?
A: See the regular postings in the
comp.sources.unix and
comp.sources.misc newsgroups, or the
full version of this list,
for information.
Section
19. System Dependencies
19.1: How can I read a single character from the
keyboard without
waiting for the RETURN key?
A: Alas, there is no standard or portable
way to do this sort of
thing in C.
19.2: How can I find out how many characters are
available for
reading, or do a non-blocking read?
A: These, too, are entirely
operating-system-specific.
19.3: How can I display a percentage-done
indication that updates
itself in place, or show one of those
"twirling baton" progress
indicators?
A: The character '\r' is a carriage return,
and '\b' is a
backspace.
19.4: How can I clear the screen, or print text in
color, or move the
cursor?
A: The only halfway-portable solution is the
curses library.
19.5: How do I read the arrow keys? What about function keys?
A: Such things depend on the keyboard,
operating system, and
library you're using.
19.6: How do I read the mouse?
A: What system are you using?
19.7: How can I do serial ("comm") port
I/O?
A: It's system-dependent.
19.8: How can I direct output to the printer?
A: See the full list for ideas.
19.9: How do I send escape sequences to control a
terminal or other
device?
A: By sending them. ESC is '\033' in ASCII.
19.10: How can I do graphics?
A: There is no portable way.
19.11: How can I check whether a file exists?
A: You can try the access() or stat()
functions. Otherwise, the
only guaranteed and portable way is to
try opening the file.
19.12: How can I find out the size of a file, prior
to reading it in?
A: You might be able to get an estimate
using stat() or fseek/ftell
(but see the full list for caveats).
19.12b:
How can I find the modification date of a file?
A: Try stat().
19.13: How can a file be shortened in-place without
completely clearing
or rewriting it?
A: There are various ways to do this, but
there is no portable
solution.
19.14: How can I insert or delete a line in the
middle of a file?
A: Short of rewriting the file, you probably
can't.
19.15: How can I recover the file name given an open
file descriptor?
A: This problem is, in general, insoluble. It is best to remember
the names of files yourself as you open
them
19.16: How can I delete a file?
A: The Standard C Library function is
remove().
19.16b:
How do I copy files?
A: Open the source and destination files and
copy a character or
block at a time, or see question 19.27.
19.17: What's wrong with the call
fopen("c:\newdir\file.dat", "r")?
A: You probably need to double those
backslashes.
19.18: How can I increase the allowable number of
simultaneously open
files?
A: Check your system documentation.
19.20: How can I read a directory in a C program?
A: See if you can use the opendir() and
readdir() functions.
19.22: How can I find out how much memory is
available?
A: Your operating system may provide a
routine which returns this
information.
19.23: How can I allocate arrays or structures
bigger than 64K?
A: Some operating systems won't let you.
19.24: What does the error message "DGROUP
exceeds 64K" mean?
A: It means that you have too much static
data.
19.25: How can I access memory located at a certain
address?
A: Set a pointer to the absolute address.
19.27: How can I invoke another program from within
a C program?
A: Use system().
19.30: How can I invoke another program and trap its
output?
A: Unix and some other systems provide a
popen() function.
19.31: How can my program discover the complete
pathname to the
executable from which it was invoked?
A: argv[0] may contain all or part of the
pathname. You may be
able to duplicate the command language
interpreter's search path
logic to locate the executable.
19.32: How can I automatically locate a program's
configuration files
in the same directory as the
executable?
A: It's hard; see also question 19.31 above.
19.33: How can a process change an environment
variable in its caller?
A: If it's possible to do so at all, it's
system dependent.
19.36: How can I read in an object file and jump to
locations in it?
A: You want a dynamic linker or loader.
19.37: How can I implement a delay, or time a user's
response, with sub-
second resolution?
A: Unfortunately, there is no portable way.
19.38: How can I trap or ignore keyboard interrupts
like control-C?
A: Use signal().
19.39: How can I handle floating-point exceptions
gracefully?
A: Take a look at matherr() and
signal(SIGFPE).
19.40: How do I...
Use sockets? Do networking? Write client/server
applications?
A: These questions have more to do with the
networking facilities
you have available than they do with C.
19.40b:
How do I... Use BIOS calls? Write ISR's?
Create TSR's?
A: These are very particular to a particular
system.
19.40c:
I'm trying to compile a program in which "union REGS" and
int86() are undefined.
A: Those have to do with MS-DOS interrupt
programming.
19.41: But I can't use all these nonstandard,
system-dependent
functions, because my program has to be
ANSI compatible!
A: That's an impossible requirement. Any real program requires at
least a few services which ANSI doesn't
define.
Section
20. Miscellaneous
20.1: How can I return multiple values from a
function?
A: Either pass pointers to several locations
which the function can
fill in, or have the function return a
structure containing the
desired values.
20.3: How do I access command-line arguments?
A: Via main()'s argv parameter.
20.5: How can I write data files which can be read
on other machines
with different data formats?
A: The most portable solution is to use text
files.
20.6: How can I call a function, given its name as
a string?
A: The most straightforward thing to do is
to maintain a
correspondence table of names and
function pointers.
20.8: How can I implement sets or arrays of bits?
A: Use arrays of char or int, with a few
macros to access the
desired bit at the proper index.
20.9: How can I determine whether a machine's byte
order is big-endian
or little-endian?
A: The usual tricks involve pointers or
unions.
20.10: How can I convert integers to binary or
hexadecimal?
A: Internally, integers are already in
binary. During I/O, you may
be able to select a base.
20.11: Can I use base-2 constants (something like
0b101010)?
Is there a printf() format for binary?
A: No, on both counts.
20.12: What is the most efficient way to count the
number of bits which
are set in an integer?
A: Many "bit-fiddling" problems
like this one can be sped up and
streamlined using lookup tables.
20.13: What's the best way of making my program
efficient?
A: By picking good algorithms and
implementing them carefully.
20.14: Are pointers really faster than arrays? How much do function
calls slow things down?
A: Precise answers to these and many similar
questions depend on
the processor and compiler in use.
20.15b:
People claim that optimizing compilers are good, but mine can't
even replace i/=2 with a shift.
A: Was i signed or unsigned?
20.15c:
How can I swap two values without using a temporary?
A: The "clever" trick is a ^= b; b
^= a; a ^= b; see also question
3.3b.
20.17: Is there a way to switch on strings?
A: Not directly.
20.18: Is there a way to have non-constant case
labels (i.e. ranges or
arbitrary expressions)?
A: No.
20.19: Are the outer parentheses in return
statements really optional?
A: Yes.
20.20: Why don't C comments nest? Are they legal inside quoted
strings?
A: C comments don't nest because PL/I's
comments don't either. The
character sequences /* and */ are not
special within double-
quoted strings.
20.20b:
What does a+++++b mean ?
A: Nothing.
It's interpreted as "a ++ ++ + b", and cannot be
parsed.
20.24: Why doesn't C have nested functions?
A: They were deliberately left out of C as a
simplification.
20.24b:
What is assert()?
A: It is a macro which documents an
assumption being made by the
programmer; it terminates the program
if the assumption is
violated.
20.25: How can I call FORTRAN (C++, BASIC, Pascal,
Ada, LISP) functions
from C?
A: The answer is entirely dependent on the
machine and the specific
calling sequences of the various
compilers in use.
20.26: Does anyone know of a program for converting
Pascal or FORTRAN
to C?
A: Several freely distributable programs are
available, namely
ptoc, p2c, and f2c. See the full list for details.
20.27: Can I use a C++ compiler to compile C code?
A: Not necessarily; C++ is not a strict
superset of C.
20.28: I need to compare two strings for close, but
not necessarily
exact, equality.
A: See the full list for ideas.
20.29: What is hashing?
A: A mapping of strings (or other data
structures) to integers, for
easier searching.
20.31: How can I find the day of the week given the
date?
A: Use mktime(), Zeller's congruence, or
some code in the full
list.
20.32: Will 2000 be a leap year?
A: Yes.
20.34: How do you write a program which produces its
own source code as
output?
A: Here's one:
char*s="char*s=%c%s%c;main(){printf(s,34,s,34);}";
main(){printf(s,34,s,34);}
20.35: What is "Duff's Device"?
A: It's a devastatingly deviously unrolled
byte-copying loop. See
the full list for details.
20.36: When will the next Obfuscated C Code Contest
be held?
How can I get a copy of previous
winning entries?
A: See the full list, or
http://www.ioccc.org/index.html .
20.37: What was the entry keyword mentioned in
K&R1?
A: It was reserved to allow functions with
multiple, differently-
named entry points, but it has been
withdrawn.
20.38: Where does the name "C" come from,
anyway?
A: C was derived from B, which was inspired
by BCPL, which was a
simplification of CPL.
20.39: How do you pronounce "char"?
A: Like the English words "char,"
"care," or "car" (your choice).
20.39b:
What do "lvalue" and "rvalue" mean?
A: An "lvalue" denotes an object
that has a location; an "rvalue"
is any expression that has a value.
C FUNDA
main()
{
char a= 'A';
if( (a=='Z')||( (a='L')&&( a=='A')))
a=a;
printf("%c",a);
printf(" Nothing ");
}
L Nothing
main()
{
static int a[5] = {2,4,6,8,10};
int i,b=5;
for(i=0; i< 5;i++){
f(a[i],&b);
printf("%d
%d\n",a[i],b);
}
}
f(x,y)
int x,*y;
{
x=*(y)+=2;
}
main()
{
printf("hello");
fork();
}
2 7
4 9
6 11
8 13
10 15
main()
{
char as[] = "\\0\0";
int i = 0;
do{
switch( as[i++]){
case '\\' : printf("A");
break;
case 0 : printf("B");
break;
default : printf("C");
break;
}
}
while(i<3);
}
Ans: ACB
main()
{
int a;
a = (1,45,012);
printf("%d", a)
}
Ans: 10
012 octal ==10 in decimal
(, , ,)
last value is taken
main()
{
int i = 10;
printf(" %d %d %d \n", ++i, i++,
++i);
}
Ans: 13 11 11
#include
main()
{
int arr[3][3] = {1,2,3,
4,5,6,
7,8,9};
int i,j;
for (j=2;j>=0;j--){
for(i=2;i>=0;i--){
printf("\n%d",*(*(arr+i)+j));
printf("\n TATATATA");
}
}
}
main()
{
int i = 5, j=10;
abc(&i,&j);
printf("%d..%d",i,j);
}
abc(int *i, int *j)
{
*i = *i + *j;
*j = *i - *j;
*i = *i - *j;
}
#define PRINT(int) printf( "int = %d
", int)
main()
{
int x=03,y=02,z=01;
PRINT (x | y & ~z);
PRINT (x & y && z);
PRINT (x ^ y & ~z);
}
main()
{
int a,b,c;
for (b=c=10;a= "Love Your INDIA \
TFy!QJu ROo TNn(ROo)SLq SLq ULo+UHs UJq
TNn*RPn/QPbEWS_JSWQAIJO^NBELP\
eHBFHT}TnALVlBLOFAKFCFQHFOQIAIREETMSQGCSQOUHATFAJKSbEALGSkMCSlOASn^r\
^r\\tZvYxXyT|S~Pn SPm SOn TNn
ULo0ULo#ULo-WHq!WFs XDt!"[b+++6];)
while(a-->64) putchar (++c=='Z'?c=c/9:33^b&1);
}
main()
{
unsigned int m[] = { 0x01,0x02, 0x04,
0x08,0x10, 0x20, 0x40, 0x80};
unsigned int n,i;
scanf("%d",&n);
for(i=0;i<=7;i++)
{ if (n& m[i])
printf("\nyes");
else
printf("\nno");
}
}
main()
{
int a,b=2,c;
int *pointer;
c = 3;
pointer = &c;
a = c/*pointer;
b = c /* assigning 3 to b*/;
printf("a = %d; b = %d", a,b);
}
main()
>{
>int i ;
>i = 1;
> i= i+2*i++;
> printf("i is now %d",i);
> }
>
>#define MAX(x,y) (x) >(y)?(x):(y)
>main()
>{
>
int i=10,j=5,k=0;
> k= MAX(i++,++j);
>
printf("%d..%d..%d",i,j,k);
> }
>
>main()
>{
>
const int i = 100;
>
int *p = &i;
>
*p = 200;
>
printf("%d\n",i);
>
>}
>
>void f(int n)
>{
>
int i;
>
for(i =1;i<=n;i++)
> f(n-i);
>
printf("done ");
>}
>main()
>{
>f(5);
>}
>
>
>void test(int , int *);
>main()
>{
>int * iptr, j, k = 2;
>iptr = &j;
>j = k;
>printf( "%d %d ", k, j);
>test(j, iptr);
>printf("%d %d\n", k, j);
>}
>void test(int l, int *p)
>{
>l++;
>(*p)++;
>}
>
>#define INFINITELOOP while(1)
>main()
>{
>
INFINITELOOP
>printf("\nHello World");
>}
>
>#include
>int myfunc(char *str)
>{
>
char *ptr =str;
>
while(*ptr++);
>
return ptr-str-1;
>}
>main()
>{
>
printf("%d", myfunc("DESIS"));
>}
>
>
>#include
>main(int sizeofargv, char *argv[])
>{
>while(sizeofargv)
>printf("%s
",argv[--sizeofargv]);
>}
>
>#include
>main()
>{
>int x,y=1,z;
>if(x=z=y); x = 3;
>printf("%d %d %d\n",x,y,z);
>while (y<4) x+=++y;
>printf("%d %d\n",x,y);
>}
>
>main()
>{
>union {
>long l_e;
>float f_e;
>} u;
>
>long l_v;
>float f_v;
>l_v = u.l_e = 10;
>printf("%f ", (float)l_v);
>printf("%f ", u.f_e);
>f_v = u.f_e = 3.555;
>printf("%d ", (long)f_v);
>printf("%d ", u.l_e);
> }
>
>
>
>void main()
>{
> char a[5] = "abcd";
> int b = 3;
>
> printf("%c\n",a[b]);
> printf("%c\n",((char *)
b)[(int) a]);
>}
>
>#define PRINTIFLESS(x,y) if((x) <
(y)) printf("First is smaller");else
>main()
>{
>
int i = 2, k =1;
>
if(i>0 && k>0) PRINTIFLESS(i,k);
>
else printf("Numbers not
greater than 0\n");
>
>}
>
>main()
>{
>int *iptr,*dptr, i;
>dptr = (int *) malloc(sizeof(i));
>iptr =&i ;
>*iptr = 10;
>free(iptr);
>*dptr = 20;
>/*dptr = iptr;*/
>free(dptr);
>printf("%d,%d,%d",*dptr,*iptr,i);
>}
>
>
>main()
>{
>char line[80];
>gets(line);
>puts(line);
>
>}
>
>main()
>{
>char c1;
>int i=0;
>c1='a';
>while(c1>='a' && c1
<='z')
>{
>c1++;
>i++;
>}
>printf("%d",i);
>}
>
>main()
>{
>char ch = 'A';
>while(ch <='F'){
>
switch(ch){
>
case 'A':case 'B':case 'C': case 'D': ch++; continue;
>
case 'E': case 'F': ch++;
>
}
>putchar(ch);
>}
>}
>
>#include
>main()
>{
>FILE *fp1,*fp2;
>fp1 =
fopen("one","w");
>fp2 =
fopen("one","w");
>fputc('A',fp1);
>fputc('B',fp2);
>fclose(fp1);
>fclose(fp2);
>}
>
>
>
>int a[50000];
>main(){
>}
>
>main()
>{
>
int a = 0xff;
>if(a<<4>>12)
>
printf("Right");
>else
>
printf("Wrong");
>}
>
>
>#include
>main()
>{
>
enum _tag{ left=10, right, front=100, back};
>
printf("left is %d, right is %d, front is %d, back is
%d",left,right,front,back);
>}
>
>#include
>main()
>{
>char *arr = "This is to
test";
>printf("\n%c %c ",*(arr),
*(arr++));
>
>}
>
>#include
>main()
>{
>int I =-3, j=2, k = 0,m;
>m = ++I && ++j || ++k;
>printf("\n%d %d %d %d", I, j,
k, m);
>}
>
>int a[50000];
>main(){}
>static int i = 6;
>
>extern i;
>main()
>{
>printf("%d",i);
>}
>
>#include
>#define MAX 20
>
>main()
>{
>
FILE *fp1, *fp2;
>
char *this1, *this2;
>
fp1 = fopen("ip1.dat","r");
>
if(fp1==NULL)printf("file open error\n");
>
>
fp2 = fopen("ip2.dat","r");
>
if(fp2==NULL)printf("file open error\n");
>
>
if((getline(this1,fp1)!=0) && (getline(this2,fp2)!=0)){
>
if(strcmp(this1,this2))
>
continue;
>
else { printf("lines do not match\n"); break;}
>
}
>}
>int getline(char *line, FILE *fp)
>{
>if(fgets(line,MAX, fp) == NULL)
>
return 0;
>else
>
return strlen(line);
>}
>
>
>#include
>main()
>{
>
FILE *fp;
>fp = fopen("testbuf.txt",
"wt");
>fwrite("1. This is
fwrite\n",1, 18, fp);
>write(fileno(fp), "2.This is write\n", 17);
>fclose(fp);
>}
>
>#define PR(a) printf("a = %d\t",(int) (a));
>#define PRINT(a) PR(a); putchar('\n');
>#define FUDGE(k) k + 3.14
>
>main()
>{
>
int x = 2;
>
PRINT( x * FUDGE(2));
>}
>
>#include
>main()
>{
>int i = 3,j;
>j = add(++i);
>printf("i = %d j = %d\n", i,
j);
>}
>
>add(ii)
>int ii;
>{
>ii++;
>printf("ii = %d\n", ii);
>}
>
>#define DEBUG(args) (printf("DEBUG:
"), printf args)
>
>main()
>{
>
int n = 0,i = 0 ;
>
printf("%d\n", n);
>
if(n != 0) DEBUG(("n is %d\n", n));
>
DEBUG(("%d",i));
>
>}
>
>main()
>{
>
char *s2, *s1 ;
>
s1* = malloc(sizeof (char) * 20);
>
s1 = "Hello, ";
>
s2 = "world!";
>
strcat(s1, s2);
>
printf("%s ", s1);
>}
>char*s="char*s=%c%s%c;main(){printf(s,34,s,34);}";
>
main(){printf(s,34,s,34);}
>main()
>{
>
char *s1 = "alpha", *s2 = "alpha";
>
if(!strcmp(s1,s2)) printf("yes\n");
>}
>
>
>#define DEBUG(args)
(printf("DEBUG: "), printf args)
>
>main()
>{
>
int n = 10;
>
if(n != 0) DEBUG(("n is %d\n", n));
>>}
>main()
>{
>int i;
>struct
>
{
>
int left,y;
>
}a;
>printf("%5d\n",a[i].left);
>}
>
>#include
>main()
>{
>char c1,c2,c3;
>c1 = getc(stdin);
>putc(c1,stdout);
>c2 = getche();
>putc(c2,stdout);
>c3 = getchar();
>putc(c3,stdout);
>}
>
>
>#include
>
>struct test{
>int f;
>};
>
>struct test*
>f(struct test * (*fPtr)() )
>{
>struct
test *ptr = (struct test*) malloc(sizeof(struct test));
>return ptr;
>}
>
>main()
>{
> f(f)->f;
>}
>
>main()
>{
>print_in_reverse( "char *str"
);
>}
>
>void print_in_reverse( char *str )
>{
>
if( *str == '\0' )
> return;
>
>
print_str_in_reverse(str+1);
>
>
printf( "%c" , *str );
>}
>
>
>
>#include
>/* #define sqrt(x) (( x < 0) ?
sqrt(-x) : sqrt(x))
>*/
>main()
>{
>int y;
>y = sqrt(-9);
>printf("%d",y);
>}
>
>
>#define MAXI 100
>main(){
>int done,i,x=6;
>done=i=0;
>for(i = 0; (i< MAXI) &&
(x/=2)>1; i++)
>done++;
>printf("%d %d\n",i,done);
>}
>#define MAXI 100
>main(){
>int done,i,x=6;
>done=i=0;
>while (i < MAXI && !done){
>if ((x/=2)>1){ i++; continue;}
>done++;
>}
>printf("%d %d\n",i,done);
>}
>main()
>{
>
struct emp
>
{ char name[20];
> int age;
> float sal;
>
};
>
struct emp e = {"Tiger"};
>
printf("\n%d %f",e.age,e.sal);
>}
>
>main()
>{
>char str[] = "Taj is 2 miles
away";
>int i;
>for(i=0;i<19;++i)
>if(isalpha(str[i]))printf("%c",toupper(str[i]));
>}
>
>
>
>main()
>{
>int c;
>
>while((c=getchar()) != 0){
>printf(" %c",c);
>}
>}
>#include
>f( )
>{
>
printf("I am f()");
>}
>extern f1( );
>main()
>{
>
int i=10;
>
f1(i);
>}
>
>f1(int i )
>{
>
printf("the i value is %d",i);
>
f();
>}
>
>#include
>#define abs(x) x>0?x:-x
>#define mabs(x) (((x)>=0)?(x):-(x))
>int fabs(int);
>main()
>{
>printf("\n%d %d",abs(10)+1,abs(-10)+1);
>printf("\n%d %d",mabs(10)+1,mabs(-10)+1);
>printf("\n%d %d\n",fabs(10)+1,fabs(-10)+1);
>}
>
>
>int fabs(int n)
>{
>return(n>0? n: -n);
>
>}
>
>unsigned char
>f(unsigned n)
>{
>
static const unsigned char table[64] = {
>
0, 0, 0, 9, 0, 0, 10, 1, 0, 0, 0, 0, 0, 11, 2, 21, 7, 0, 0, 0, 0,
0, 0,
>
15, 0, 0, 12, 0, 17, 3, 22, 27, 32, 8, 0, 0, 0, 0, 0, 20, 6, 0, 0,
14,
>
0, 0, 16, 26, 31, 0, 0, 19, 5, 13, 0, 25, 30, 18, 4, 24, 29, 23,
28, 0
>
};
>
return table[((n & -n) * 0x1d0d73df) >> 26];
>}
>main()
>{
>printf("%c",f(8));
>}
>#include
>int myfunc(char *str)
>{
>
char *ptr =str;
>
while(*ptr++);
>
return ptr-str-1;
>}
>main()
>{
>
printf("length is %d", myfunc("DESIS"));
>}
>
>
>#include
>struct _tag
>{
>
int i;
>
union
>
{
> int a;
> int b;
>
}c;
>} a;
>
>main()
>{
>
a.c.a=10;
>
printf("test %d\n",a.c.b);
>}
>
>main()
>{
>
int a=10,b;
>
b=a>=5?100:200;
>
printf("%d\n",b);
>}
>
>
>#define MAXI 100
>main(){
>int x=6,done,i;
>done=i=0;
>do
>{
>
if((x/=2)>1)
> {i++; continue;}
>
else
> done++;
>}while ((i < MAXI) &&
!done);
>
>printf("%d %d\n",i,done);
>}
>#include
>main()
>{
>extern int i;
>i=20;
>printf("%d\n",sizeof(i));
>}
>
>fun()
>{
>printf("Yes\n");
>}
>
>#define fun() printf("No\n")
>
>main()
>{
>
fun();
>
(fun)();
>}
>
>main()
>{
>
int i = 1;
>
switch(i) {
> printf("\nHello, ");
> case 1: printf("One,
");
> i++;
> break;
> case 2:
printf("Two");
> break;
> }
>}
>
>
>#define DESHAWCURRENTDEBUGLEVEL 1
>
>void main(void)
>{
>int i = 10 ;
>int j = 15 ;
>
>#ifdef DESHAWCURRENTDEBUGLEVEL
>printf("%d\n",i);
>#else
>printf("%d\n",j);
>#endif
>}
>
>#define scanf "%s DE Shaw"
>main()
>{
> printf(scanf,scanf);
> }
>
>main()
>{
> char *p="abc";
> char *q="abc123";
>
>
while(*p==*q)
>
{
>
printf("%c %c",*p,*q);
>
p++;q++;
>
}
>}
>#define INTPTR int *
>main()
>{
>
INTPTR pi, pj;
>
int i,j;
>
i=10;j=20;
>
pi = &j;
>
pj = &j;
>
j++;
>
i= *pi;
>
printf("%d,",i);
>
j++;
>
i= *pj;
>
printf("%d",i);
>}
>
>#include
>main()
>{
>char strp[] = "Never ever say
no";
>char *chp, c='e';
>int i,j;
>chp = strrchr(strp, c);
>i = chp-strp;
>for(j=0;j<=i;j++)printf("%c",strp[j]);
>}
>#include
>main()
>{
>
char str[] ="abcdef";
>
printf("str is %s",str);
>
str = "DESIS";
>
printf("str is %s",str);
>}
>
>
>main()
>{
>
char *str ="India pvt. ltd.";
>
char *str1 = "DESIS";
>
printf("str is
%s",str);
>
printf("str is %s",str1);
>
strcat(str1,str);
>
printf("str is %s",str1);
>}
>
>main()
>{
>
char str[] ="DESIS India pvt. ltd.";
>
const char *str1= str;
>
strcpy(str1,"DESHAW");
>
printf("str is
%s",str);
>}
>
>main()
>{
>int i=4,j=2,k=0;
>char c1='a',c2='b';
>if(k==0)printf("k is
zero\n");
>else if(j==2)printf("j is
2\n");
>else if(i==4)printf("i is
4\n");
>if(c1!='a')printf("c1 is not
a\n");
>else if (c2=='a')printf("c2 is
b");
>else printf("Hello\n");
>}
>
>#include
>main()
>{
>int a[3] = {1,2,3};
>int i= 2;
>printf("\n %d %d\n", a[i],
i[a]);
>}
>#include
>void fun(int, int*);
>main()
>{
>int j,i;
>int * intptr;
>printf("enter an integer\n");
>scanf("%d",&i);
>intptr = &j;
>j = i;
>printf("i and j are %d %d
\n",i,j);
>fun(j,intptr);
>printf("i is:%d",i);
>printf("\n j is:%d",j);
>}
>void fun(int k, int *iptr)
>{
>k++;
>(*iptr)++;
>return;
>}
>
>#include
>main()
>{
> int x;
>
x = printf("%d\n",x=printf("%d",890));
>
printf("%d",x);
>
}
>
>#include
>main()
>{
>int i;
>char c;
>for (i=0;i<5;i++){
>
scanf("%d",&c);
>
printf("%d",i);
>
}
>}
>
>main()
>{
>
int x = 10,y=2,z;
>
z=x/*y+y*/+y;
>
printf("%d\n",z);
>}
>main()
>{
>int a[] = {0,1,2,3,4};
>int *p[] = {a,a+1,a+2,a+3,a+4};
>int **pp = p;
>
>printf("%d, %d, %d ", *pp-a,
pp-p, **pp);
>pp++; pp++;;++pp;*++pp;
>printf("%d, %d, %d ", pp-p,
*pp-a, **pp);
>}
>
>main()
>{
>int a[] = {0,1,2,3,4};
>int *p[] = {a,a+1,a+2,a+3,a+4};
>int **pp = p;
>
>printf("%d, %d, %d ", *pp-a,
pp-p, **pp);
>pp++; *pp++;++pp;*++pp;
>printf("%d, %d, %d ", pp-p,
*pp-a, **pp);
>}
>
>main()
>{
>char input[] =
"SSSWILTECH1\1\1";
>int i, c;
>for ( i=2; (c=input[i])!='\0'; i++){
>
switch(c){
> case 'a': putchar ('i');
continue;
> case '1': break;
> case 1: while (( c = input[++i])
!= '\1' && c!= '\0');
> case 9: putchar('S');
> case 'E': case 'L': continue;
> default: putchar(c);continue;
> }
> putchar(' ');
> }
> putchar('\n');
>}
>
>
>main(){
>unsigned int k = 987 , i = 0;
>char trans[10];
>
>
do {
> trans[i++] = (k%16 > 9) ? (k%16 - 10 + 'a') : (k%16 -
'0' );
>
> } while(k /= 16);
>
>
for(i=0;i<10;i++) printf("%c", trans[i]);
>}
>
>
>
>main()
>{
>unsigned int k = 987 , i = 0;
>char trans[10];
>
>
do {
>
trans[i++] = (k%16 > 9 ? k%16
- 10 + 'a' : k%16 - '0' );
>
printf("%d %d\n",k,k%16);
>
>
} while(k /= 16);
>
> printf("%s\n", trans);
> }
>
>
>main()
>{
>char *pk;
>const char* p;
>const char c = 'a';
>char c1='b';
>p=&c1;
>pk = &c;
>printf("%c %c",*pk,*p);
>}
>
>main()
>{
>int i=4;
>if (i>5) printf("Hi");
>else f(i);
>}
>
>f(int j)
>{
>if (j>=4) f(j-1);
>else if(j==0)return;
>printf("Hi");
>}
>
>
>int *NEXT(register int i)
>{
>int *ipt;
>ipt = &i;
>ipt++;
>return ipt;
>}
>
>main ()
>{
>int j;
>printf("%d",(NEXT(j)));
>}
>
>
>#define PRINT(int) printf("int =
%d ",int)
>main()
>{
>int x,y,z;
>x=03;y=02;z=01;
>PRINT(x^x);
>z<<=3;PRINT(x);
>y>>=3;PRINT(y);
>}
>
>
>#define PRINT(int) printf( "int =
%d ", int)
>main()
>{
>int x=03,y=02,z=01;
>PRINT (x | y & ~z);
>PRINT (x & y && z);
>PRINT (x ^ y & ~z);
>}
>
>
>main()
>{
>int p;
>for(p = 1; p<=10, --p ; p=p+2)
>
puts("Hello");
>}
>
>#include
>int n, R;
>main()
>{
>R = 0;
>scanf("%d",&n);
>printf("\n %d, %d",fun(n),R);
>}
>
>int fun(int n)
>{
>if (n>3) return
>
R = 5;
>
R = 6;
>
return(1);
>
>
}
>main()
>{
>int a = 10, b = 5,c = 3,d = 3;
>
>if ((a
>
>else
printf(" %d %d %d %d
", a, b, c, d);
>
>}
>
>
>
>
>main()
>{
>struct test
>{
>char c;
>int i;
>char v;
>} t1;
>printf("%d %d\n",sizeof(t1),
sizeof(t1.c));
>}
>
>#include
>main()
>{
>int a,b;
>scanf("%d %d", &a,
&b);
>printf("%d\n", a+++b);
>printf("%d %d\n",a,b);
>}
>
>float
s=1944,x[5],y[5],z[5],r[5],j,h,a,b,d,e;int i=33,c,l,f=1;int
g(){return f=
>(f*6478+1)%65346;}m(){x[i]=g()-l;y[i]=(g()-l)/4;r[i]=g()>>4;}main(){char
t[1948
>]="
`MYmtw%FFlj%Jqig~%`jqig~Etsqnsj3stb",*p=t+3,*k="3tjlq9TX";l=s*20;while(i
>p[i++]='\n'+5;for(i=0;i<5;i++)z[i]=(i?z[i-1]:0)+l/3+!m();while(1){for(c=33;c
>c++){c+=!((c+1)%81);j=c/s-.5;h=c%81/40.0-1;p[c]=37;for(i=4;i+1;i--)if((b=(a=h*x
>[i]+j*y[i]+z[i])*a-(d=1+j*j+h*h)*(-r[i]*r[i]+x[i]*x[i]+y[i]*y[i]+z[i]*z[i]))>0)
>{for(e=b;e*e>b*1.01||e*e
>(i=4;i+1;z[i]-=s/2,i--)z[i]=z[i]<0?l*2+!m():z[i];while(i
>
>int
i;
>main()
>{
>
char a[] = "Shiva";
>
printf("%c\n",i[a]);
>}
>
>
>
>myread(a,b)
>{
>
printf("%d %d",a,b);
>}
>
>main()
>{
>
myread(2,4);
>}
>
>
>
>funct(char* str)
>{
>
printf("%s\n",str);
>}
>
>main()
>{
>
static int ii = 1;
>
int jj = 5;
>
ii+=++jj;
>
funct(ii+++"Campus Interview");
>}
>
>
>funct(str)
>{
>
printf("%s\n",str);
>}
>
>main()
>{
>
funct('-'-'-'+"DEShaw");
>}
>
>main()
>{
>
printf(" %d\n",'-'-'-'-'/'/'/');
>
}
>
>static int
a = 6;
>extern int a;
>
>main()
>{
>
printf("%d",a);
>
}
>
>#include
>main()
>{
>int i=6,j=4;
>printf("NO\n");
>switch(i)
>{
>do{
>case 1: printf("yes\n");
>
>case 2:
>
>case 3:
>
>case 4:
>
>case 5:
>
>case 6:
>
j--;
>
}while (j);
>
}
>
}
>
>#include
>main()
>{
>auto int i = 0;
>printf("%d\n",i);
>
{
>
int i = 2;
>
printf("%d\n",i);
>
{
> i+=1;
> printf("%d\n",i);
> }
>
printf("%d\n",i);
>
}
>printf("%d\n",i);
>printf("%d\n",reset());
>printf("%d\n",ret10());
>printf("%d\n",reset());
>printf("%d\n",ret10());
>}
>
>
>int reset()
>{
>int j = 0;
>return(j);
>}
>
>int ret10()
>{
>static int i = 10;
>i+=1;
>return(i);
>}
>
>#include
>#include
>main()
>{
>struct emp1
>{
>
char *name;
>
int age;
>};
>struct emp2
>{
>char *cp;
>struct emp1 e1;
>}e2 = {"ghi",{"jkl",123}};
>
>struct emp1 e3 =
{"rwer",2341};
>printf("\n%s
%d\n",e3.name,e3.age);
>printf("\n%s %s
%d\n",e2.cp,e2.e1.name,e2.e1.age);
>}
>
>struct xyz{
>
int xyz ;
>
}
>
;
>
>main()
>{
>union xyz{
>
int xyz;
>
}
>
;
>
}
>
>#include
>main()
>{
>char s[] = "Bouquets and
Brickbats";
>printf("\n%c,
",*(&s[2]));
>printf("%s, ",s+5);
>printf("\n%s",s);
>printf("\n%c",*(s+2));
>}
>#include
>struct s
>
{
>
char *st;
>
struct s *sptr;
>
};
>main()
>{
>int i;
>struct s *p[3];
>static struct s a[]={
>
{"abcd",a+1},
>
{"pqrs",a+2},
>
{"stuv",a}
>
};
>for( i=0;i<3;i++ )p[i] = a[i].sptr;
>swap(*p,a);
>printf("%s %s %s
\n",p[0]->st,(*p)->st, (*p)->sptr->st);
>}
>
>swap(p1,p2)
>struct s *p1,*p2;
>{
>char *temp;
>temp = p1->st;
>p1->st = p2->st;
>p2->st = temp;
>}
>
>Swap( int *x , int *y)
>{
>int tmp = *x ;
>*y = *x ;
>*x = tmp;
>}
>main()
>{
>int a = 1, b = 2;
>Swap(&a, &b);
>printf("%d %d\n", a, b);
>}
>main()
>{
>
int i;
>
scanf("%d",&i);
>
switch(i) {
> printf("\nHello");
> case 1:
printf("\none");
> break;
> case 2:
printf("\ntwo");
> break;
> }
>}
>
>#include
>main()
>{
>int x;
>x = 3;
>f(x);
>printf("MAIN");
>
>}
>
>f(int n)
>{
>printf("F");
>if (n != 0)
>f(n-1);
>}
>
>#include
>#include
>
>main()
>{
>
>
int ptr[] = {1,2,23,6,5,6};
>
char str[] =
{'a','b','c','d','e','f','g','h'};
>
> printf("pointer
differences are %ld, %d",&ptr[3], &str[3]-&str[0]);
> }
>
>#include
>main()
>{
>char a,b,c;
>scanf("%c %c
%c",&a,&b,&c);
>printf("%c %c %c ", a, b, c);
>}
>
>#include
>main()
>{
>
int a = 10000;
>
char b='c';
>
>
int i,j;
>
/* i=printf("%d\n",a);
>
>
j=printf("%c\n",b);*/
>
>
printf("%d,%d",printf("%d\n",a),printf("%c\n",b));
>
>
}
>#include
>#define PR(a) printf("%d\t",(int) (a));
>#define PRINT(a,b,c) PR(a);PR(b);PR(c);
>#define MAX(a,b) (a
>main(){
>
int x = 1,y = 2;
> PRINT(MAX(x++,y),x,y);
> PRINT(MAX(x++,y),x,y);
> }
>
>#include
>main()
>{
> unsigned int i=100;
>for(;i>=0;i--) printf("hello: %u\n",i);
>}
>
>main()
>{
>
>struct list{
>int x;
>struct ist next;
>}head;
>
>struct ist{
>int x;
>int y;
>};
>head.x = 100;
>head.next.x=10;
>printf("%d %d", head.x,head.next.x);
>}
>
>
>main()
>{
>typedef union
>{
>struct
>{
>char c1,c2;
>} s;
>long j;
>float x;
>} U;
>
>U example;
>example.s.c1 = 'a';
>example.s.c2 = 'b';
>example.j = 5;
>printf("%c %c %d",
example.s.c1, example.s.c2, example.j);
>}
>
>
>main()
>
{
> struct s1
> { char *str;
> struct s1 *ptr;
> };
> static struct s1 arr[] = { {"Hyderabad",arr+1},
>
{"Bangalore",arr+2},
>
{"Delhi",arr}
> };
> struct s1 *p[3];
> int i;
>
> for(i=0;i<=2;i++)
> p[i] = arr[i].ptr;
>
>
printf("%s\n",(*p)->str);
>
printf("%s\n",(++*p)->str);
>
printf("%s\n",((*p)++)->str);
>
}
>
>main()
>
{struct s1
> { char *str;
> struct s1 *ptr;
> };
> static struct s1 arr[] = { {"Hyderabad",arr+1},
>
{"Bangalore",arr+2},
>
{"Delhi",arr}
> };
> struct s1 *p[3];
> int i;
>
> for(i=0;i<=2;i++) p[i] = arr[i].ptr;
>
>printf("%s ",(*p)->str);
> printf("%s
",(++*p)->str);
>printf("%s
",((*p)++)->str);
>
}
>
>
>main()
>{
>char input[] =
"SSSWILTECH1\1\1";
>int i, c;
>for ( i=2; (c=input[i])!='\0'; i++){
>
switch(c){
> case 'a': putchar ('i');
continue;
> case '1': break;
> case 1: while (( c = input[++i])
!= '\1' && c!= '\0');
> case 9: putchar('S');
> case 'E': case 'L': continue;
> default: putchar(c);continue;
> }
> putchar(' ');
>
}
>
putchar('\n');
>}
>
>main()
>{
>int i, n, m, b, x[25];
>int f1(int, int, int j[25]);
>for(i=0;i<25;i++) x[i] = i;
>i=0; m = 24;
>b=f1(i, m, x);
>printf("res %d\n",b);
>}
>
>int f1( int p, int q, int a[25])
>{
>int m1,m2;
>if (q==0)
>return(a[p]);
>else
>{
>m1 = f1 (p, q/2, a);
>m2 = f1(p+q/2+1,q/2,a);
>if(m1
>return (m2);
>else
>return(m1);
>}
>}
>main()
>{
>int a[3][4]
={1,2,3,4,5,6,7,8,9,10,11,12} ;
>int i,j,k=99 ;
>for(i=0;i<3;i++)
>for(j=0;j<4;j++)
>if(a[i][j] < k) k = a[i][j];
>printf("%d", k);
>}
>main()
>{
>char *p = "hello world!";
>p[0] = 'H';
>printf("%s",p);
>}
Bottom of Form 1
************************ CITICORP
***********************************
1]. The following variable is available in
file1.c
static int average_float;
all the functions in the file1.c can access the variable
[2]. extern int x;
Check the answer
[3]. Another Problem with
# define TRUE 0
some code
while(TRUE)
{
some code
}
This won't go into the loop as TRUE is defined as 0
[4].
A question in structures where the memebers are dd,mm,yy.
mm:dd:yy
09:07:97
[5]. Another structure question
1 Rajiv System Analyst
[6].
INFILE.DAT is copied to OUTFILE.DAT
[7]. A question with argc and argv .
Input will be
c:\TEMP.EXE Ramco Systems India
-----------------------------------------------------------------------
main()
{
int x=10,y=15;
x=x++;
y=++y;
printf("%d %d\n",x,y);
}
----------------------------------------------------------------------
int x;
main()
{
int x=0;
{
int x=10;
x++;
change_value(x);
x++;
Modify_value();
printf("First output:
%d\n",x);
}
x++;
change_value(x);
printf("Second Output : %d\n",x);
Modify_value();
printf("Third Output : %d\n",x);
}
Modify_value()
{
return (x+=10);
}
change_value()
{
return(x+=1);
}
----------------------------------------------------------------------------
main()
{
int x=20,y=35;
x = y++ + x++;
y = ++y + ++x;
printf("%d %d\n",x,y);
}
-----------------------------------------------------------------------
main()
{
char *p1="Name";
char *p2;
p2=(char *)malloc(20);
while(*p2++=*p1++);
printf("%s\n",p2);
}
----------------------------------------------------------------------
main()
{
int x=5;
printf("%d %d %d\n",x,x<<2,x>>2);
}
--------------------------------------------------------------------
#define swap1(a,b) a=a+b;b=a-b;a=a-b;
main()
{
int x=5,y=10;
swap1(x,y);
printf("%d %d\n",x,y);
swap2(x,y);
printf("%d %d\n",x,y);
}
int swap2(int a,int b)
{
int temp;
temp=a;
b=a;
a=temp;
return;
}
----------------------------------------------------------------------
main()
{
char *ptr = "Ramco Systems";
(*ptr)++;
printf("%s\n",ptr);
ptr++;
printf("%s\n",ptr);
}
---------------------------------------------------------------------
#include
main()
{
char s1[]="Ramco";
char s2[]="Systems";
s1=s2;
printf("%s",s1);
}
-----------------------------------------------------------------
#include
main()
{
char *p1;
char *p2;
p1=(char *) malloc(25);
p2=(char *) malloc(25);
strcpy(p1,"Ramco");
strcpy(p2,"Systems");
strcat(p1,p2);
printf("%s",p1);
}
C
QUESTIONS:WHAT IS THE OUT PUT FOR FOLLOWING PROGRAMMS
1)main()
{
char a[2];
*a[0]=7;
*a[1]=5;
printf("%d",&a[1]-a)
ANS:
ans may be 1.(illegal initialization)
2)
#include
main(){
char a[]="hellow";
char *b="hellow";
char c[5]="hellow";
printf("%s %s %s ",a,b,c);
printf("
",sizeof(a),sizeof(b),sizeof(c));
}
(ans is
hellow,hellow,hellow
6,2,5 )
3)
#include
main()
float value=10.00;
printf("%g %0.2g %0.4g
%f",value,value,value,value)
}
(ans is 10,10,10,10.000000)
4)
#include
void function1;
int i-value=100;
main()
{
i-value=50;
function1;
printf("i-value in the
function=",i-value);
printf("i-value after the
function=",i-value);
}
printf("i-value at the end of
main=",i-value);
functioni()
i-value=25;
THIS IS ROUGH IDEA OF THE PROGRAM
ANS ARE
1)i-value in the function=25;
2)i-value after the function=50;
3)i-value at the end of the main=100;
5)
main()
{
funct(int n);
{
switch(n)
case1:
m=2;
break;
case2:
m=5;
break;
case3:
m=7;
break;
default:
m=0;
}
THIS IS ROUGH IDEA:
(ANS:Out put is m=0)
I am sending mainly c paper and some
questions.Rao also will send somethig.There are 15 c q's all are discriptive.
1)fallacy
f()
{
int a;
void c;f2(&c,&a);
2)a=0;
b=(a=0)?2:3;
a) What will be the value of b? why
b) If in 1st stmt a=0 is replaced by -1,
b=?
c) If in second stmt a=0 is replaced by -1,
b=?
3)char *a[2]
int const *p;
int *const p;
struct new { int a;int b; *var[5] (struct
new)
4)f()
{
int a=2;
f1(a++);
}
f1(int c)
{
printf("%d", c);
}
c=?
5)f1()
{
f(3);}
f(int t)
{
switch(t);
{
case 2: c=3;
case 3: c=4;
case 4: c=5;
case 5: c=6;
default: c=0;}
value of c?
6)Fallacy
int *f1()
{
int a=5;
return &a;
}
f()
int *b=f1()
int c=*b;
}
7)a)Function returning an int pointer
b)Function ptr returning an int ptr
c)Function ptr returning an array of
integers
d)array of function ptr returning an array
of integers
(See Scham series book)
8)fallacy
int a;
short b;
b=a;
9)Define function ?Explain about arguments?
10)C passes
By value or By reference?
11)Post processed code for
abc=1;
b=abc1; (1 or 2 blank lines are given)
strcpy(s,"abc");
z=abc;
12)difference between my-strcpy and strcpy
?check
13)f()
{
int *b;
*b=2;
}
14)Function which gives a pointer to a
binary trees const an integer value
at each code, return function of all the
nodes in binary tree.(Study)Check
15)Calling refernce draw the diagram of
function stack illustrating the
variables in the -----then were pushed on
the stack at the point when
function f2 has been introduced
type def struct
{ double x,double y} point;
main( int argc, char *arg[3])
{double a;
int b,c;
f1(a,b);}
f1(double x, int y)
{
point p;
stack int n;
f2(p,x,y)}
f2(point p, double angle)
{ int i,j,k,int max)
}
________________________________________________________
1. main(){
int
mat[3][3] = { 1,2,3,4,5,6,7,8,9 };
int
i, j;
for
( i = 2; i >= 0 ; i-- )
for
( j = 2; j >= 0 ; j-- )
printf("%d",
*(*mat+j)+i);
}
a). 9 8 7 6 5 4 3 2 1 b). 1 2 3 4 5 6 7 8 9
c). 9 6 3 8 5 2 7 4 1 d). None of the above
2. main() {
printf("Hello\n");
fork();
printf("Hi\n");
}
You are supposed to justify your answer in
interview.
3. int count = 10, *temp, sum = 0;
temp = &count;
*temp = 20;
temp = ∑
*temp = count;
printf("%d %d %d\n", count *temp, sum);
(a). 10 20 0 (b). 20 20 20 (c).
20 20 10 (d). None of the above
4. main()
{
enm
tag = { left = 10, right, front = 100, back };
printf("%d
%d %d %d", left, right, front, back);
}
(a). compile time error b). 10 11 100 101 (c). 10 11 12 13 (d).
1 2 3 4
5. What is the value of i if you pass value
of i to
the following function?
foo(const int &j) {
j++;
}
(a). Compile error (b). 10 (c).
prints addition of I (d).
11
6. You are reading from inpur file to
buffer. Buffer terminates with NULL, the char you need is ch.Write a C program.
7. Write a program to add 10 between 100
and total is not initialezed.
8. while ( (*p++ = *q++) != 0 ) { }
What does the above line of C code do ?
Same as strcpy() in C.
9. main()
{
int
n = 3;
f(n);
printf("MAIN");
}
void f(int n) {
printf("F");
if
( n != 0 )
f(n-1);
}
What is the output of the above code? Ans.
FFFF
10. main()
{
char
s[] = "Never ever look it" , *ch, c = 'e' ;
int
i, j;
chr
= strcmp ( s, c);
i
= chr - s;
for
( i = 0; i < j; i++ )
printf("%d",
s[i] );
}
What is the o/p of the program ?
(a). Never eve (b). Never ev (c).
error (d).
None of the above
11. main()
{
union
u {
struct
s {
char c1, c2;
};
long
x;
float
y;
};
u
example ;
example.s.c1
= 'a' ;
example.s.c2
= 'b' ;
example.x
= 5;
printf("%c
%c %d", example.s.c1, example.s.c2, example.x);
}
(a). a b 5 b).
0 0 5 (c). garbage garbage 5 (Correct) (d). error
12 main()
{
int
i, j, k = 0;
char
c1 = 'a', c2 = 'b';
if
( k == 0 )
printf("K
is zero");
else
-----
-----
if
( c1 != 'a' )
printf("c2
== b");
else
if ( c2 == 'a' )
printf("c1
== a");
else
printf("Hello");
}
(a). K is zero c1 == a
(b).
" c2 == b
(c).
" Hello (Correct) (d).
error
13. If you don't declare a function and you
are calling in main(), Does C support this or not ?
14. When a function returns where form the
memory allocated? Ans.
Stack
15. void (*((int, void (*)())));
Ans. (c)