C Interview Questions
1 what is the difference between a
while statement and a do statement?
Ans: A while
statement checks at the beginning of a loop to see whether the next loop
iteration should occur. A do statement checks at the end of a loop to see whether
the next iteration of a loop should occur. The do statement will always execute
the body of a loop at least once.
2 what is the difference between a break statement and a
continue statement?
Ans: A break
statement results in the termination of the statement to which it applies
(switch, for, do, or while). A continue statement is used to end the current
loop iteration and return control to the loop statement.
3 what does break and continue statements do?
Ans: Continue
statement continues the current loop (if label not specified) in a new
iteration whereas break statement exits the current loop.
4 how can you tell what shell you are running on unix
system?
Ans: You can
do the Echo $RANDOM. It will return a undefined variable if you are from the
C-Shell, just a return prompt if you are from the Bourne shell, and a 5 digit
random numbers if you are from the Korn shell. You could also do a ps -l and
look for the shell with the highest PID.
5 what is the difference between a pointer and a reference?
Ans: You can
do the Echo $RANDOM. It will return a undefined variable if you are from the
C-Shell, just a return prompt if you are from the Bourne shell, and a 5 digit
random numbers if you are from the Korn shell. You could also do a ps -l and
look for the shell with the highest PID.
6 How do you print an address?
Ans: The
safest way is to use printf() (or fprintf() or sprintf()) with the %P
specification. That prints a void pointer (void*). Different compilers might
print. a pointer with different formats. Your compiler will pick a format
that’s right for your environment. If you have some other kind of pointer (not
a void*) and you want to be very safe, cast the pointer to a void*:
printf( “%Pn”, (void*) buffer ).
7 Can math operations be performed on a void pointer?
Ans: No.
Pointer addition and subtraction are based on advancing the pointer by a number
of elements. By definition, if you have a void pointer, you don’t know what
it’s pointing to, so you don’t know the size of what it’s pointing to. If you
want pointer arithmetic to work on raw addresses, use character pointers.
8 How can you determine the size of an allocated portion of
memory?
Ans: You
can’t, really. free() can , but there’s no way for your program to know the
trick free() uses. Even if you disassemble the library and discover the trick,
there’s no guarantee the trick won’t change with the next release of the
compiler.
9 what is a null pointer?
Ans: There is
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.
1) To stop indirection in a recursive data structure
2) As an error value
3) As a sentinel value.
10 Is NULL always defined as 0?
Ans: NULL is
defined as either 0 or (void*)0. These values are almost identical; either a
literal zero or a void pointer is converted automatically to any kind of
pointer, asNecessary, whenever a pointer is needed (although the compiler can’t
always tell when a pointer is needed).
11 Difference between arrays and pointers?
Ans: 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.
Arrays use subscripted variables to access and manipulate data. Array variables can be
Equivalently written using pointer expression.
12 Are pointers integers?
Ans: pointers
are not integers. A pointer is an address. It is merely a positive number and
not an integer.
13 How are pointer variables?
Ans: Pointer
variable are initialized by one of the following two ways
Static memory allocation
Dynamic memory allocation.
Static memory allocation
Dynamic memory allocation.
14 What are the advantages of the pointer?
Ans:
Debugging is easier
It is easier to understand the logic involved in the program
Testing is easier
Recursive call is possible
Irrelevant details in the user point of view are hidden in functions
It is easier to understand the logic involved in the program
Testing is easier
Recursive call is possible
Irrelevant details in the user point of view are hidden in functions
Functions are
helpful in generalizing the Program
15 What is a pointer value and Address?
Ans: A
pointer value is a data object that refers to a memory location. Each memory
location is numbered in the memory. The number attached to a memory location is
called the address of the location.
16 What is a pointer variable?
Ans: A
pointer variable is a variable that may contain the address of another variable
or any valid address in the memory.
17 What is static memory allocation and dynamic memory
allocation?
Ans: Static
memory allocation: The compiler allocates the required memory space for a
declared variable. By using the address of operator, the reserved address is
obtained and this address may be assigned to a pointer variable. Since most of
the declared variable
Have static memory, this way of assigning pointer value to a pointer variable is known as static memory allocation. Memory is assigned during compilation time.
Have static memory, this way of assigning pointer value to a pointer variable is known as static memory allocation. Memory is assigned during compilation time.
Dynamic
memory allocation: It uses functions such as malloc ( ) or calloc ( ) to get
memory dynamically. If these functions are used to get memory dynamically and
the values returned by these functions are assigned to pointer variables, such
assignments are known as dynamic memory allocation. Memory is assigned during
run time.
18 What is the purpose of main ( )
Ans: The
function main ( ) invokes other functions within it. It is the first function
to
Be called when the program starts execution.
It is the starting function
It returns an int value to the environment that called the program
Recursive call is allowed for main ( ) also.
It is a user-defined function
Program execution ends when the closing brace of the function main ( ) is reached.
It has two arguments 1) argument count and 2) argument vector (represents strings passed).
Any user-defined name can also be used as parameters for main ( ) instead of argc and argv
Be called when the program starts execution.
It is the starting function
It returns an int value to the environment that called the program
Recursive call is allowed for main ( ) also.
It is a user-defined function
Program execution ends when the closing brace of the function main ( ) is reached.
It has two arguments 1) argument count and 2) argument vector (represents strings passed).
Any user-defined name can also be used as parameters for main ( ) instead of argc and argv
19 What is the purpose of realloc ( )?
Ans: The
function realloc (ptr, n) uses two arguments. the first argument ptr is a
pointer to a block of memory for which the size is to be altered. The second
argument n specifies the new size. The size may be increased or decreased. If n
is greater than the old size and
If sufficient space is not available subsequent to the old region, the function realloc ( )
may create a new region and all the old data are moved to the new region.
If sufficient space is not available subsequent to the old region, the function realloc ( )
may create a new region and all the old data are moved to the new region.
20 What are the advantages of auto variables?
Ans: 1) The
same auto variable name can be used in different blocks
2) There is no side effect by changing the values in the blocks
3) The memory is economically used
4) Auto variables have inherent protection because of local scope
2) There is no side effect by changing the values in the blocks
3) The memory is economically used
4) Auto variables have inherent protection because of local scope
C++
Interview Questions
1 What is a class?
Ans: Class is
a user-defined data type in C++. It can be created to solve a particular kind
of problem. After creation the user need not know the specifics of the working
of a class.
2 What is an object?
Ans: Object is a software bundle of variables and related methods. Objects have state and behavior.
Ans: Object is a software bundle of variables and related methods. Objects have state and behavior.
3 What is a template?
Ans:
Templates allow to create generic functions that admit any data type as
parameters and return value without having to overload the function with all
the possible data types. Until certain point they fulfill the functionality of
a macro. Its prototype is any of the two following ones: template
function_declaration; template function_declaration;
The only
difference between both prototypes is the use of keyword class or typename, its
use is indistinct since both expressions have exactly the same meaning and
behave exactly the same way.
4 What is abstraction?
Ans:
Abstraction is of the process of hiding unwanted details from the user.
5 What is virtual constructors/ destructors?
Ans:
Virtual destructors: If an object (with a non-virtual destructor) is destroyed
explicitly by applying the delete operator to a base-class pointer to the
object, the base-class destructor function (matching the pointer type) is
called on the object. There is a simple solution to this problem – declare a
virtual base-class destructor. This makes allderived-class destructors virtual
even though they don’t have the same name as the base-class destructor. Now, if
the object in the hierarchy is destroyed explicitly by applying the delete
operator to a base-class pointer to a derived-class object, the destructor for
the appropriate class is called. Virtual constructor: Constructors cannot be
virtual. Declaring a constructor as a virtual function is a syntax error. Does
c++ support multilevel andmultiple inheritance? Yes. What are the advantages of
inheritance?
• It permits code reusability.
• Reusability saves time in program development.
• It encourages the reuse of proven and debugged
high-quality software, thus reducing problem after a system becomes functional. What is the difference between declaration and definition? The declaration tells the compiler that at some later point we plan to present the definition of this declaration. E.g.: void stars () //function declaration The definition contains the actual implementation.
E.g.: void stars () // declarator
{
for(int j=10; j>=0; j–) //function body
cout<<”*”;
cout<}
• It permits code reusability.
• Reusability saves time in program development.
• It encourages the reuse of proven and debugged
high-quality software, thus reducing problem after a system becomes functional. What is the difference between declaration and definition? The declaration tells the compiler that at some later point we plan to present the definition of this declaration. E.g.: void stars () //function declaration The definition contains the actual implementation.
E.g.: void stars () // declarator
{
for(int j=10; j>=0; j–) //function body
cout<<”*”;
cout<}
6 what is the difference between an object and a class?
Ans:Classes
and objects are separate but related concepts. Every object belongs to a class
and every class contains one or more related objects.
Ø A Class is
static. All of the attributes of a class are fixed before, during, and after
theexecution of a program. The attributes of a class don’t change.
Ø The class
to which an object belongs is also (usually) static. If a particular object
belongs to a certain class at the time that it is created then it almost
certainly will still belong to that class right up until the time that it is
destroyed.
Ø An Object
on the other hand has a limited lifespan. Objects are created and
eventuallydestroyed. Also during that lifetime, the attributes of the object
may undergo significant change.
7 What is the difference between class and structure?
Ans:
Structure: Initially (in C) a structure was used to bundle different type of
data types together to perform a particular functionality. But C++ extended the
structure to contain functions also. The major difference is that all
declarations inside a structure are by default public. Class: Class is a
successor of Structure. By default all the members inside the class are
private.
8 What is virtual class and friend ?
Ans: Friend
classes are used when two or more classes are designed to work together and
need access to each other’s implementation in ways that the rest of the
world shouldn’t be allowed to have. In other words, they help keep
private things private. For instance, it may be desirable for class Database Cursor
to have more privilege to the internals of class Database than main() has.
9 What is polymorphism? Explain with an example?
Ans:”Poly”
means “many” and “morph” means “form”. Polymorphism is the ability of an object
(or reference) to assume (be replaced by) or become many different forms of
object. Example: function overloading, function overriding, virtual functions.
Another example can be a plus ‘+’ sign, used for adding two integers or for
using it to concatenate two strings.
10 What is public, protected, private?
Ans:Public,
protected and private are three access specifiers in C++.
Ø Public data members and member functions are accessible outside the class.
Ø Protected data members and member functions are only available to derived classes.
Ø Private data members and member functions can’t be accessed outside the class. However there is an exception can be using friend classes.
Ø Public data members and member functions are accessible outside the class.
Ø Protected data members and member functions are only available to derived classes.
Ø Private data members and member functions can’t be accessed outside the class. However there is an exception can be using friend classes.
11 What is RTTI?
Ans: Runtime
type identification (RTTI) lets you find the dynamic type of an object when you
have only a pointer or a reference to the base type. RTTI is the official way
in standard C++ to discover the type of an object and to convert the type of a
pointer or reference (that is, dynamic typing). The need came from practical
experience with C++. RTTI replaces many homegrown versions with a solid,
consistent approach.
12 What is friend function?
Ans: As the
name suggests, the function acts as a friend to a class. As a friend of a
class, it can access its private and protected members. A friend function is
not a member of the class. But it must be listed in the class definition.
13 What is function overloading and operator overloading?
Ans: Function
overloading: C++ enables several functions of the same name to be defined, as
long as these functions have different sets of parameters (at least as far as
their types are concerned). This capability is called function overloading.
When an overloaded function is called, the C++ compiler selects the proper
function by examining the number, types and order of the arguments in the call.
Function overloading is commonly used to create several functions of the same
name that perform similar tasks but on different data types. Operator
overloading allows existing C++ operators to be redefined so that they work on
objects of user-defined classes. Overloaded operators are syntactic sugar for
equivalent function calls. They form a pleasant facade that doesn’t add
anything fundamental to the language (but they can improve understandability
and reduce maintenance costs).
14 What is namespace?
Ans:
Namespaces allow us to group a set of global classes, objects and/or functions
under a name. To say it somehow, they serve to split the global scope in
sub-scopes known as namespaces. The form to use namespaces is: namespace
identifier { namespace-body } Where identifier is any valid identifier and
namespace-body is the set of classes, objects and functions that are included
within the namespace.
For example:
namespace
general { int a, b; } In this case, a and b are normal variables integrated
within the general namespace. In order to access to these variables from
outside the namespace we have to use the scope operator.
For example:
to access the previous variables we would have to put: general’s general::b The
functionality of namespaces is specially useful in case that there is a
possibility that a global object or function can have the same name than
another one, causing a redefinition error.
15 What do you mean by inline function?
Ans:The idea
behind inline functions is to insert the code of a called function at the point
where the function is called. If done carefully, this can improve the
application’s performance in exchange for increased compile time and possibly
(but not always) an increase in the size of the generated binary executables.
16 What do you mean by pure virtual functions?
Ans:Answer A
pure virtual member function is a member function that the base class forces
derived classes to provide. Normally these member functions have no
implementation. Pure virtual functions are equated to zero. class Shape {
public: virtual void draw() = 0;
};
};
17 What is a scope resolution operator?
Ans: A scope
resolution operator (::), can be used to define the member functions of a class
outside the class.
18 Difference between realloc() and free()?
Ans: The free
subroutine frees a block of memory previously allocated by the malloc
subroutine. Undefined results occur if the Pointer parameter is not a valid
pointer. If the Pointer parameter is a null value, no action will occur. The
realloc subroutine changes the size of the block of memory pointed to by the
Pointer parameter to the number of bytes specified by the Size parameter and
returns a new pointer to the block. The pointer specified by the Pointer
parameter must have been created with the malloc, calloc, or realloc
subroutines and not been deal located with the free or realloc subroutines.
Undefined results occur if the Pointer parameter is not a valid pointer.
19 What are virtual functions?
Ans: A
virtual function allows derived classes to replace the implementation provided
by the base class. The compiler makes sure the replacement is always called
whenever the object in question is actually of the derived class, even if the
object is accessed by a base pointer rather than a derived pointer. This allows
algorithms in the base class to be replaced in the derived class, even if users
don’t know about the derived class.
20 Explain kill() and its possible return values?
Ans:There are
four possible results from this call: ‘kill()’ returns 0. This implies that a
process exists with the given PID, and the system would allow you to send
signals to it. It is system-dependent whether the process could be a zombie.
‘kill()’ returns -1, ‘errno == ESRCH’ either no process exists with the given
PID, or security enhancements are causing the system to deny its existence. (On
some systems, the process could be a zombie.) ‘kill()’ returns -1, ‘errno ==
EPERM’ the system would not allow you to kill the specified process. This means
that either the process exists (again, it could be a zombie) or draconian
security enhancements are present (e.g. your process is not allowed to send
signals to *anybody*). ‘kill()’ returns -1, with some other value of ‘errno’
you are in trouble! The most-used technique is to assume that success or
failure with ‘EPERM’ implies that the process exists, and any other error
implies that it doesn’t. An alternative exists, if you are writing specifically
for a system (or all those systems) that provide a ‘/proc’ filesystem: checking
for the existence of ‘/proc/PID’ may work.
1. How can I search for data in a
linked list?
Unfortunately,
the only way to search a linked list is with a linear search, because the only
way a linked list’s members can be accessed is sequentially. Sometimes it is
quicker to take the data from a linked list and store it in a different data
structure so that searches can be more efficient
2. What is impact of signed numbers on the memory?
Sign of the
number is the first bit of the storage allocated for that number. So you get
one bit less for storing the number. For example if you are storing an 8-bit
number, without sign, the range is 0-255. If you decide to store sign you get 7
bits for the number plus one bit for the sign. So the range is -128 to +127.
3. What is precision?
Precision
refers the accuracy of the decimal portion of a value. Precision is the number
of digits allowed after the decimal point.
4. What is the data structures used to perform recursion?
Stack.
Because of its LIFO (Last In First Out) property it remembers its caller so
knows whom to return when the function has to return. Recursion makes use of
system stack for storing the return addresses of the function calls. Every
recursive function has its equivalent iterative (non-recursive) function. Even
when such equivalent iterative procedures are written, explicit stack is to be
used.
5. What is placement new?
When you want
to call a constructor directly, you use the placement new. Sometimes you have
some raw memory that’s already been allocated, and you need to construct an
object in the memory you have. Operator new’s special version placement new
allows you to do it.
class Widget
{
public :
Widget(int widgetsize);
…
Widget* Construct_widget_int_buffer(void *buffer,int widgetsize)
{
return new(buffer) Widget(widgetsize);
}
};
This function returns a pointer to a Widget object that’s constructed within the buffer passed to the function. Such a function might be useful for applications using shared memory or memory-mapped I/O, because objects in such applications must be placed at specific addresses or in memory allocated by special routines.
class Widget
{
public :
Widget(int widgetsize);
…
Widget* Construct_widget_int_buffer(void *buffer,int widgetsize)
{
return new(buffer) Widget(widgetsize);
}
};
This function returns a pointer to a Widget object that’s constructed within the buffer passed to the function. Such a function might be useful for applications using shared memory or memory-mapped I/O, because objects in such applications must be placed at specific addresses or in memory allocated by special routines.
6. What is the easiest sorting method to use?
The answer is
the standard library function qsort(). It’s the easiest sort by far for several
reasons:
It is already written.
It is already debugged.
It has been optimized as much as possible (usually).
Void qsort(void *buf, size_t num, size_t size, int (*comp)(const void *ele1, const void *ele2));
It is already written.
It is already debugged.
It has been optimized as much as possible (usually).
Void qsort(void *buf, size_t num, size_t size, int (*comp)(const void *ele1, const void *ele2));
7. What is a node class?
A node class is a class that, relies on the base class for services and implementation, provides a wider interface to users than its base class, relies primarily on virtual functions in its public interface depends on all its direct and indirect base class can be understood only in the context of the base class can be used as base for further derivation
A node class is a class that, relies on the base class for services and implementation, provides a wider interface to users than its base class, relies primarily on virtual functions in its public interface depends on all its direct and indirect base class can be understood only in the context of the base class can be used as base for further derivation
Can be used
to create objects. A node class is a class that has added new services or
functionality beyond the services inherited from its base class
8. What is the quickest sorting method to use?
The answer
depends on what you mean by quickest. For most sorting problems, it just
doesn’t matter how quick the sort is because it is done infrequently or other
operations take significantly more time anyway. Even in cases in which sorting
speed is of the essence, there is no one answer. It depends on not only the
size and nature of the data, but also the likely order. No algorithm is best in
all cases. There are three sorting methods in this author’s toolbox that are
all very fast and that are useful in different situations. Those methods are
quick sort, merge sort, and radix sort.
The Quick
Sort
The quick sort algorithm is of the divide and conquer type. That means it works by reducing a sorting problem into several easier sorting problems and solving each of them. A dividing value is chosen from the input data, and the data is partitioned into three sets: elements that belong before the dividing value, the value itself, and elements that come after the dividing value. The partitioning is performed by exchanging elements that are in the first set but belong in the third with elements that are in the third set but belong in the first Elements that are equal to the dividing element can be put in any of the three sets the algorithm will still work properly.
The quick sort algorithm is of the divide and conquer type. That means it works by reducing a sorting problem into several easier sorting problems and solving each of them. A dividing value is chosen from the input data, and the data is partitioned into three sets: elements that belong before the dividing value, the value itself, and elements that come after the dividing value. The partitioning is performed by exchanging elements that are in the first set but belong in the third with elements that are in the third set but belong in the first Elements that are equal to the dividing element can be put in any of the three sets the algorithm will still work properly.
The Merge
Sort
The merge sort is a divide and conquer sort as well. It works by considering the data to be sorted as a sequence of already-sorted lists (in the worst case, each list is one element long). Adjacent sorted lists are merged into larger sorted lists until there is a single sorted list containing all the elements. The merge sort is good at sorting lists and other data structures that are not in arrays, and it can be used to sort things that don’t fit into memory. It also can be implemented as a stable sort.
The merge sort is a divide and conquer sort as well. It works by considering the data to be sorted as a sequence of already-sorted lists (in the worst case, each list is one element long). Adjacent sorted lists are merged into larger sorted lists until there is a single sorted list containing all the elements. The merge sort is good at sorting lists and other data structures that are not in arrays, and it can be used to sort things that don’t fit into memory. It also can be implemented as a stable sort.
The Radix Sort
The radix sort takes a list of integers and puts each element on a smaller list, depending on the value of its least significant byte. Then the small lists are concatenated, and the process is repeated for each more significant byte until the list is sorted. The radix sort is simpler to implement on fixed-length data such as ints.
The radix sort takes a list of integers and puts each element on a smaller list, depending on the value of its least significant byte. Then the small lists are concatenated, and the process is repeated for each more significant byte until the list is sorted. The radix sort is simpler to implement on fixed-length data such as ints.
9.How can I search for data in a linked list?
Unfortunately,
the only way to search a linked list is with a linear search, because the only
way a linked list’s members can be accessed is sequentially. Sometimes it is
quicker to take the data from a linked list and store it in a different data
structure so that searches can be more efficient.
Comments
Post a Comment