Friday, July 16, 2010

C Interview Questions

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
//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

3. What is a register variable?
Register variables are stored in the CPU registers. Its default value is a garbage value. Scope of a register variable is local to the block in which it is defined. Lifetime is till control remains within the block in which the register variable is defined. Variable stored in a CPU register can always be accessed faster than the one that is stored in memory. Therefore, if a variable is used at many places in a program, it is better to declare its storage class as register

Example:
register int x=5;
Variables for loop counters can be declared as register. Note that register keyword may be gnored by some compilers.

4. Where is an auto variables stored?
Main memory and CPU registers are the two memory locations where auto variables are stored. Auto variables are defined under automatic storage class. They are stored in main memory. Memory is allocated to an automatic variable when the block which contains it is called and it is de-allocated at the completion of its block execution.
Auto variables:
Storage :
Default value :
Scope
Lifetime
:
:
main memory.
garbage value.
local to the block in which the variable is defined.
till the control remains within the block in which the variable is defined.

5. What is scope & storage allocation of extern and global variables?
Extern variables: belong to the External storage class and are stored in the main memory. extern is used when we have to refer a function or variable that is implemented in other file in the same project. The scope of the extern variables is Global.

Example:
/***************
Index: f1.c
****************/
#include
extern int x;
int main() {
printf("value of x %d", x);
return 0;
}

Index: f2.c
****************/
int x = 3;

Here, the program written in file f1.c has the main function and reference to variable x. The file f2.c has the declaration of variable x. The compiler should know the datatype of x and this is done by extern definition. Global variables: are variables which are declared above the main( ) function. These variables are accessible throughout the program. They can be accessed by all the functions in the program. Their default value is zero.

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
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.

What is the difference between 'break' and 'continue' statements?
Differences between 'break' and 'continue' statements
break
1. break is a keyword used to terminate the loop or
exit from the block. The control jumps to next
statement after the loop or block.
2.Syntax:
{
Statement 1;
Statement 2;
Statement n;
break;
}
continue

1. continue is a keyword used for skipping the current iteration and go to next iteration of the loop

2.Syntax:

{
Statement 1;
continue;
Statement 2;
}

3. break can be used with for, while, do- while, and switch statements. When break is used in nested loops i.e. within the inner most loop then only the innermost loop is terminated.

4. Example:

i = 1, j = 0;
while(i<=5)
{
i=i+1;
if(i== 2)

3. This statement when occurs in a loop does not terminate it but skips the statements after this continue statement. The control goes to the next iteration. continue can be used with for, while and do-while.
4. Example:
i = 1, j = 0;
while(i<=5)
{
i=i+1;
if(i== 2)

10. 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
int main() {
int i;
for (i = 1; i <= 5; i++) {
//print the number
printf("\n %d", i);
}
return 0;
}

Output:
1
2
3
4
5

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.

What is an Enumeration Constant?
Enumeration is a data type. We can create our own data type and define values that the variable can take. This can help in making program more readable. enum definition is similar to that of a structure.

Example: consider light_status as a data type. It can have two possible values - on or off.
enum light_status
{
on, off
};
enum light_status bulb1, bulb2;
/* bulb1, bulb2 are the variables */

Declaration of enum has two parts:
a) First part declares the data type and specifies the possible values, called 'enumerators'.
b) Second part declares the variables of this data type.
We can give values to these variables:
bulb1 = on;
bulb2 = off;

5. What is a structure?
A structure is a collection of pre-defined data types to create a user-defined data type. Let us say we need to create records of students. Each student has three fields:
int roll_number;
char name[30];
int total_marks;
This concept would be particularly useful in grouping data types. You could declare a structure student as:
struct student
{
int roll_number;
char name[30];
int total_marks;
} student1, student2;
The above snippet of code would declare a structure by name student and it initializes two objects student1, student2. Now these objects and their fields could be accessed by saying student1.roll_number for accesing roll number field of student1 object, similarly student2.name for accesing name field of student2 object.


What are the advantages of unions?
Union is a collection of data items of different data types. It can hold data of only one member at a time though it has members of different data types. If a union has two members of different data types, they are allocated the same memory. The memory allocated is equal to maximum size of the members. The data is interpreted in bytes depending on which member is being accessed.

Example:
union pen
{
char name;
float point;
};

Here name and point are union members. Out of these two variables, 'point' is larger variable which is of float data type and it would need 4 bytes of memory. Therefore 4 bytes space is allocated for both the variables. Both the variables have the same memory location. They are accessed according to their type. Union is efficient when members of it are not required to be accessed at the same time.


How can typedef be to define a type of structure?
typedef declaration helps to make source code of a C program more readable. Its purpose is to redefine the name of an existing variable type. It provides a short and meaningful way to call a data type. typedef is useful when the name of the data type is long. Use of typedef can reduce length and complexity of data types.
Note: Usually uppercase letters are used to make it clear that we are dealing with our own data type.

Example:
struct employee
{
char name[20];
int age;
};



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
/* 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




Explain command line arguments of main function?
In C, we can supply arguments to 'main' function. The arguments that we pass to main ( ) at command prompt are called command line arguments. These arguments are supplied at the time of invoking the program. The main ( ) function can take arguments as: main(int argc, char *argv[]) { }
The first argument argc is known as 'argument counter'. It represents the number of arguments in the command line. The second argument argv is known as 'argument vector'. It is an array of char type pointers that points to the command line arguments. Size of this array will be equal to the value of argc.

Example: at the command prompt if we give:
C:\> fruit.exe apple mango
then
argc would contain value 3
argv [0] would contain base address of string " fruit.exe" which is the command name that invokes the program.
argv [1] would contain base address of string "apple"
argv [2] would contain base address of string "mango"
here apple and mango are the arguments passed to the program fruit.exe





What are header files? Are functions declared or defined in header files ?
Functions and macros are declared in header files. Header files would be included in source files by the compiler at the time of compilation.
Header files are included in source code using #include directive.#include includes all the declarations present in the header file 'some.h'.
A header file may contain declarations of sub-routines, functions, macros and also variables which we may want to use in our program. Header files help in reduction of repetitive code.

Syntax of include directive:
#include //includes the header file stdio.h, standard input output header into the source code

Functions can be declared as well as defined in header files. But it is recommended only to declare functions and not to define in the header files. When we include a header file in our program we actually are including all the functions, macros and variables declared in it.

In case of pre-defined C standard library header files ex(stdio.h), the functions calls are replaced by equivalent binary code present in the pre-compiled libraries. Code for C standard functions are linked and then the program is executed. Header files with custom names can also be created.

Program: Custom header files example
/****************
Index: restaurant.h
****************/
int billAll(int food_cost, int tax, int tip);

/****************
Index: restaurant.c
****************/
#include
int billAll(int food_cost, int tax, int tip) {
int result;
result = food_cost + tax + tip;
printf("Total bill is %d\n",result);
return result;
}


What are the differences between formal arguments and actual arguments of a function?
Argument: An argument is an expression which is passed to a function by its caller (or macro by its invoker) in order for the function(or macro) to perform its task. It is an expression in the comma-separated list bound by the parentheses in a function call expression.

Actual arguments:
The arguments that are passed in a function call are called actual arguments. These arguments are defined in the calling function.

Formal arguments:
The formal arguments are the parameters/arguments in a function declaration. The scope of formal arguments is local to the function definition in which they are used. Formal arguments belong to the called function. Formal arguments are a copy of the actual arguments. A change in formal arguments would not be reflected in the actual arguments.



What is a pointer in C?
A pointer is a special variable in C language meant just to store address of any other variable or function. Pointer variables unlike ordinary variables cannot be operated with all the arithmetic operations such as '*','%' operators. It follows a special arithmetic called as pointer arithmetic.

A pointer is declared as:
int *ap;
int a = 5;

In the above two statements an integer a was declared and initialized to 5. A pointer to an integer with name ap was declared.

Next before ap is used
ap=&a;
This operation would initialize the declared pointer to int. The pointer ap is now said to point to a.

Operations on a pointer:
• Dereferencing operator ' * ': This operator gives the value at the address pointed by the pointer . For example after the above C statements if we give
printf("%d",*ap);

Actual value of a that is 5 would be printed. That is because ap points to a.

• Addition operator ' + ': Pointer arithmetic is different from ordinary arithmetic.


. What are the advantages of using pointers?
Pointers are special variables which store address of some other variables.

Syntax: datatype *ptr;
Here * indicates that ptr is a pointer variable which represents value stored at a particular address.

Example: int *p;
'p' is a pointer variable pointing to address location where an integer type is stored.

Advantages:
1. Pointers allow us to pass values to functions using call by reference. This is useful when large sized arrays are passed as arguments to functions. A function can return more than one value by using call by reference.
2. Dynamic allocation of memory is possible with the help of pointers.
3. We can resize data structures. For instance, if an array's memory is fixed, it cannot be resized. But in case of an array whose memory is created out of malloc can be resized.
4. Pointers point to physical memory and allow quicker access to data.



What are the differences between malloc() and calloc()?
Allocation of memory at the time of execution is called dynamic memory allocation. It is done using the standard library functions malloc() and calloc(). It is defined in "stdlib.h".

malloc(): used to allocate required number of bytes in memory at runtime. It takes one argument, viz. size in bytes to be allocated.

Syntax:
void * malloc(size_t size);


Example:
a = (int*) malloc(4);
4 is the size (in bytes) of memory to be allocated.

calloc(): used to allocate required number of bytes in memory at runtime. It needs two arguments viz.,
1. total number of data and
2. size of each data.

Syntax:
void * calloc(size_t nmemb, size_t size);
Example:
a = (int*) calloc(8, sizeof(int));
Here sizeof indicates the size of the data type and 8 indicates that we want to reserve space for storing 8 integers.

Differences between malloc() and calloc() are:
1. Number of arguments differ.
2. By default, memory allocated by malloc() contains garbage values. Whereas memory allocated by calloc() contains all zeros.


How to use realloc() to dynamically increase size of an already allocated array?
realloc(): This function is used to increase or decrease the size of any dynamic memory which is allocated using malloc() or calloc() functions.

Syntax: void *realloc(void *ptr, size_t newsize);

The first argument 'ptr' is a pointer to the memory previously allocated by the malloc or calloc functions. The second argument 'newsize' is the size in bytes, of a new memory region to be allocated by realloc. This value can be larger or smaller than the previously allocated memory. The realloc function adjusts the old memory region if newsize is smaller than the size of old memory.

If the newsize is larger than the existing memory size, it increases the size by copying the contents of old memory region to new memory region. The function then deallocates the old memory region. realloc function is helpful in managing a dynamic array whose size may change during execution.

Example: a program that reads input from standard input may not know the size of data in advance. In this case, dynamically allocated array can be used so that it is possible allocate the exact amount of memory using realloc function.

No comments:

Post a Comment