Tuesday 24 July 2012

C Based interview questions

SHARE

1. What is the difference between declaring a variable and defining a variable?


Declaration of a variable in C hints the compiler about the type and size of the variable in compile time. Similarly,
declaration of a function hints about type and size of function parameters. No space is reserved in memory for
any variable in case of declaration.


Example: int a;
Here variable 'a' is declared of data type 'int'


Defining a variable means declaring it and also allocating space to hold it.
We can say "Definition = Declaration + Space reservation".


Example: int a = 10;
Here variable "a" is described as an int to the compiler and memory is allocated to hold value 10.






2. What is a static variable?

A static variable is a special variable that is stored in the data segment unlike the default automatic variable that
is stored in stack. A static variable can be initialized by using keyword static before variable name.


Example:
static int a = 5;
A static variable behaves in a different manner depending upon whether it is a global variable or a local variable.
A static global variable is same as an ordinary global variable except that it cannot be accessed by other files in
the same program / project even with the use of keyword extern. A static local variable is different from local
variable. It is initialized only once no matter how many times that function in which it resides is called. It may be
used as a count variable.


Example:
#include <stdio.h>
//program in file f1.c
void count(void) {
static int count1 = 0;
int count2 = 0;
count1++;
count2++;
printf("\nValue of count1 is %d, Value of count2 is %d", count1, count2);
}/


*Main function*/
int main(){
count();
count();
count();
return 0;
}


Output:
Value of count1 is 1, Value of count2 is 1
Value of count1 is 2, Value of count2 is 1
Value of count1 is 3, Value of count2 is 1




3. printf() Function


What is the output of printf("%d")?


1. When we write printf("%d",x); this means compiler will print the
value of x. But as here, there is nothing after %d so compiler will show
in output window garbage value.


2. When we use %d the compiler internally uses it to access the
argument in the stack (argument stack). Ideally compiler determines
the offset of the data variable depending on the format specification
string. Now when we write printf("%d",a) then compiler first accesses
the top most element in the argument stack of the printf which is %d
and depending on the format string it calculated to offset to the actual
data variable in the memory which is to be printed. Now when only %d
will be present in the printf then compiler will calculate the correct
offset (which will be the offset to access the integer variable) but as
the actual data object is to be printed is not present at that memory
location so it will print what ever will be the contents of that memory
location.


3. Some compilers check the format string and will generate an error
without the proper number and type of arguments for things like
printf(...) and scanf(...).




4. malloc() Function- What is the difference between "calloc(...)" and
"malloc(...)"?


1. calloc(...) allocates a block of memory for an array of elements of a
certain size. By default the block is initialized to 0. The total number of
memory allocated will be (number_of_elements * size).
malloc(...) takes in only a single argument which is the memory
required in bytes. malloc(...) allocated bytes of memory and not blocks
of memory like calloc(...).


2. malloc(...) allocates memory blocks and returns a void pointer to the
allocated space, or NULL if there is insufficient memory available.
calloc(...) allocates an array in memory with elements initialized to 0
and returns a pointer to the allocated space. calloc(...) calls malloc(...)
in order to use the C++ _set_new_mode function to set the new
handler mode.




5. printf() Function- What is the difference between "printf(...)" and
"sprintf(...)"?


sprintf(...) writes data to the character array whereas printf(...) writes data to the
standard output device.
Compilation How to reduce a final size of executable?
Size of the final executable can be reduced using dynamic linking for
libraries.




6. What is scope & storage allocation of register, static and local variables?
Register variables: belong to the register storage class and are stored in the CPU registers. The scope of the
register variables is local to the block in which the variables are defined. The variables which are used for more
number of times in a program are declared as register variables for faster access.


Example: loop counter variables.
register int y=6;
Static variables: Memory is allocated at the beginning of the program execution and it is reallocated only after
the program terminates. The scope of the static variables is local to the block in which the variables are defined.


Example:
#include <stdio.h>
void decrement(){
static int a=5;
a--;
printf("Value of a:%d\n", a);
} int main(){
decrement();
return 0;
}
Here 'a' is initialized only once. Every time this function is called, 'a' does not get initialized. so output would be 4
3 2 etc.,


Local variables: are variables which are declared within any function or a block. They can be accessed only by
function or block in which they are declared. Their default value is a garbage value.




7. What is the difference between 'for' and 'while' loops?


for loop: When it is desired to do initialization, condition check and increment/decrement in a single statement of
an iterative loop, it is recommended to use 'for' loop.


Syntax:
for(initialization;condition;increment/decrement)
{/
/block of statements
increment or decrement
}
Program: Program to illustrate for loop
#include<stdio.h>
int main() {
int i;
for (i = 1; i <= 5; i++) {
//print the number
printf("\n %d", i);
}
return 0;
}


Output:
12345


Explanation:
The loop repeats for 5 times and prints value of 'i' each time. 'i' increases by 1 for every cycle of loop.


while loop: When it is not necessary to do initialization, condition check and increment/decrement in a single
statement of an iterative loop, while loop could be used. In while loop statement, only condition statement is
present.


Syntax:
#include<stdio.h>
int main() {
int i = 0, flag = 0;while (flag == 0) {
if (a[i] == 54) {
//as element is found, flag = 1,the loop terminates
flag = 1;
}
else {
i++;
}
}
printf("Element found at %d th location", i);
return 0;
}


Output:
Element found at 5th location


Explanation:
Here flag is initialized to zero. 'while' loop repeats until the value of flag is zero, increments i by 1. 'if' condition
checks whether number 54 is found. If found, value of flag is set to 1 and 'while' loop terminates.
int a[10] = { 0, 1, 4, 6, 89, 54, 78, 25, 635, 500 };
//This loop is repeated until the condition is false.




8.What is the difference between strings and character arrays?
A major difference is: string will have static storage duration, whereas
as a character array will not, unless it is explicity specified by using the
static keyword.




Actually, a string is a character array with following properties:


* the multibyte character sequence, to which we generally call string,
is used to initialize an array of static storage duration. The size of this
array is just sufficient to contain these characters plus the terminating
NUL character.


* it not specified what happens if this array, i.e., string, is modified.


* Two strings of same value[1] may share same memory area. For
example, in the following declarations:
char *s1 = “Calvin and Hobbes”;
char *s2 = “Calvin and Hobbes”;
the strings pointed by s1 and s2 may reside in the same memory
location. But, it is not true for the following:
char ca1[] = “Calvin and Hobbes”;
char ca2[] = “Calvin and Hobbes”;
[1] The value of a string is the sequence of the values of the contained
characters, in order.




9. Difference between const char* p and char const* p


In const char* p, the character pointed by ‘p’ is constant, so u cant
change the value of character pointed by p but u can make ‘p’ refer to
some other location.


in char const* p, the ptr ‘p’ is constant not the character referenced by
it, so u cant make ‘p’ to reference to any other location but u can
change the value of the char pointed by ‘p’.


10. What is equivalent of multiplying an unsigned int by 2: left shift of number by 1 or right shift of
number by 1?


Left shifting of an unsigned integer is equivalent to multiplying an unsigned int by 2.


Eg1: 14<<1;


Consider a number 14-----00001110 (8+4+2)is its binary equivalent
left shift it by 1--------------00011100(16+8+4) which is 28.


Eg2: 1<<1;


consider the number as 1---00000001(0+0+1).
left shift that by 1------------00000010(0+2+0) which is 2.
left shift by 1 bit of a number=2*number
left shift by 1 bit of 2*number=2*2*number
left shift by n bits of number=(2^n)*number


Program: Program to illustrate left shift and right shift operations.


#include<stdio.h>
int main(void)
{
int x=10,y=10;
printf("left shift of 10 is %d \n",x<<1);
printf("right shift of 10 is %d \n",y>>1);
return 0;
}


Output:
left shift of 10 is 20
right shift of 10 is 5


Explanation:
Left shift (by 1 position) multiplies a number by two. Right shift divides a number by 2.


11. What are the differences between a structure and a union?
Structures and Unions are used to store members of different data types.


STRUCTURE 


a)Declaration:
struct
{
data type member1;
data type member2;
};


b)Every structure member is allocated memory when
a structure variable is defined.


Example:


struct emp {
char name[5];
int age;
float sal;
};
struct emp e1;
Memory allocated for structure is 1+2+4=7 bytes. 1
byte for name, 2 bytes for age and 4 bytes for sal.


UNION


a)Declaration:
union
{
data type member1;
data type member2;
};


b)The memory equivalent to the largest item is allocated
commonly for all members.


Example:


union emp1 {
char name[5];
int age;
float sal;
};
union emp1 e2;
Memory allocated to a union is equal to size of the
largest member. In this case, float is the largest-sized
data type. Hence memory allocated to this union is 4
bytes.


12. What is a null pointer?


There are times when it’s necessary to have a pointer that doesn’t
point to anything. The macro NULL, defined in , has a value that’s
guaranteed to be different from any valid pointer. NULL is a literal zero,
possibly cast to void* or char*. Some people, notably C++
programmers, prefer to use 0 rather than NULL.
The null pointer is used in three ways:
1) To stop indirection in a recursive data structure
2) As an error value
3) As a sentinel value


13. How are pointer variables initialized?


Pointer variable are initialized by one of the following two ways
- Static memory allocation
- Dynamic memory allocation




14. Difference between arrays and pointers?


- Pointers are used to manipulate data using the address. Pointers use
* operator to access the data pointed to by them
- Arrays use subscripted variables to access and manipulate data.
Array variables can be equivalently written using pointer expression.


15. What is the purpose of main() function?
In C, program execution starts from the main() function. Every C program must contain a main() function. The
main function may contain any number of statements. These statements are executed sequentially in the order
which they are written.
The main function can in-turn call other functions. When main calls a function, it passes the execution control to
that function. The function returns control to main when a return statement is executed or when end of function is
reached.


In C, the function prototype of the 'main' is one of the following:
int main(); //main with no arguments
int main(int argc, char *argv[]); //main with arguments
The parameters argc and argv respectively give the number and value of the program's command-line
arguments.


Example:


#include <stdio.h>
/* program section begins here */
int main() {
// opening brace - program execution starts here
printf("Welcome to the world of C");
return 0;
}/
/ closing brace - program terminates here


Output:


Welcome to the world of C
SHARE

Author: verified_user