Você está na página 1de 130

What is a "RTTI"?

RTTI as known Runtime Type Identification.


If you want to cast the object of one class as the object of another class so u require to know the
type of the object at the runtime and u may want to cofirm is tht object of the same class you want to
change we use the typeid operator to check what is the objects type and then use dynamic cast to
cast the object.

C++ Questions
• What are the major differences between C and C++?
o What are the differences between new and malloc?
o What is the difference between delete and delete[]?
o What are the differences between a struct in C and in C++?
o What are the advantages/disadvantages of using #define?
o What are the advantages/disadvantages of using inline and const?
• What is the difference between a pointer and a reference?
o When would you use a pointer? A reference?
o What does it mean to take the address of a reference?
• What does it mean to declare a function or variable as static?
• What is the order of initalization for data?
• What is name mangling/name decoration?
o What kind of problems does name mangling cause?
o How do you work around them?
• What is a class?
o What are the differences between a struct and a class in C++?
o What is the difference between public, private, and protected access?
o For class CFoo { }; what default methods will the compiler generate
for you>?
o How can you force the compiler to not generate them?
o What is the purpose of a constructor? Destructor?
o What is a constructor initializer list?
o When must you use a constructor initializer list?
o What is a:
 Constructor?
 Destructor?
 Default constructor?
 Copy constructor?
 Conversion constructor?
o What does it mean to declare a...
 member function as virtual?
 member function as static?
 member function as static?
 member variable as static?
 destructor as static?
o Can you explain the term "resource acquisition is initialization?"
o What is a "pure virtual" member function?
o What is the difference between public, private, and protected inheritance?
o What is virtual inheritance?
o What is placement new?
o What is the difference between operator new and the new operator?
• What is exception handling?
o Explain what happens when an exception is thrown in C++.
o What happens if an exception is not caught?
o What happens if an exception is throws from an object's constructor?
o What happens if an exception is throws from an object's destructor?
o What are the costs and benefits of using exceptions?
o When would you choose to return an error code rather than throw an
exception?
• What is a template?
• What is partial specialization or template specialization?
• How can you force instantiation of a template?
• What is an iterator?
• What is an algorithm (in terms of the STL/C++ standard library)?
• What is std::auto_ptr?
• What is wrong with this statement? std::auto_ptr ptr(new char[10]);
• It is possible to build a C++ compiler on top of a C compiler. How would you do
this? (Note: I've only asked this question once; and yes, he understood that I was
asking him how cfront was put together. We hired him.)

Code Snippets
I like to put these up on a whiteboard, and ask questions about them.

What output does the following code generate? Why?


What output does it generate if you make A::Foo() a pure virtual function?

#include <iostream>

using namespace std;

class A {
public:
A() {
this->Foo();
}
virtual void Foo() {
cout << "A::Foo()" << endl;
}
};

class B : public A {
public:
B() {
this->Foo();
}
virtual void Foo() {
cout << "B::Foo()" << endl;
}
};

int main(int, char**)


{
B objectB;

return 0;
}

What output does this program generate as shown? Why?

#include <iostream>

using namespace std;

class A {
public:
A() {
cout << "A::A()" << endl;
}
~A() {
cout << "A::~A()" << endl; throw
"A::exception";
}
};

class B {
public:
B() {
cout << "B::B()" << endl; throw
"B::exception";
}
~B() {
cout << "B::~B()";
}
};

int main(int, char**) {


try {
cout << "Entering try...catch block" <<
endl;

A objectA;
B objectB;

cout << "Exiting try...catch block" <<


endl;
} catch (char* ex) {
cout << ex << endl;
}

return 0;
}

1. What's the difference between the keywords struct and class?


2. What is a reference?
3. What happens if you assign to a reference?
4. What happens if you return a reference?
5. What does object.method1().method2() mean?
6. How can you reseat a reference to make it refer to a different
object?
7. When should I use references, and when should I use pointers?
8. What is a handle to an object?
9. Why should I use inline functions instead of plain old #define
macros?
10. How do you tell the compiler to make a non-member function inline?
11. Can one constructor of a class call another constructor of the
same
class to initialize the this object?
12. Should you use the this pointer in the constructor?
13. What is the "Named Constructor Idiom"?
14. Why can't I initialize my static member data in my constructor's
initialization list?
15. Why are classes with static data members getting linker errors?
16. How can I handle a constructor that fails?
17. What is the "Named Parameter Idiom"?
18. What's the order that local objects are destructed?
19. Can I overload the destructor for my class?
20. Should I explicitly call a destructor on a local variable?
21. What if I want a local to "die" before the close } of the scope
in which
it was created? Can I call a destructor on a local if I really want to?
22. OK, OK already; I won't explicitly call the destructor of a
local; but
how do I handle the above situation?
23. But can I explicitly call a destructor if I've allocated my
object with
new?
24. When I write a destructor, do I need to explicitly call the
destructors
for my member objects?
25. When I write a derived class's destructor, do I need to
explicitly call
the destructor for my base class?
26. Should my destructor throw an exception when it detects a problem?
27. Is there a way to force new to allocate memory from a specific
memory
area?
28. What is "self assignment"?
29. Can I overload operator== so it lets me compare two char[] using a
string comparison?
30. Can I create a operator** for "to-the-power-of" operations?
31. Should I design my classes from the outside (interfaces first) or
from
the inside (data first)?
32. Do friends violate encapsulation?
33. ] What does it mean that "friendship isn't inherited, transitive,
or
reciprocal"?
34. Should my class declare a member function or a friend function?
35. Why does my program go into an infinite loop when someone enters
an
invalid input character?
36. How can I open a stream in binary mode?
37. In p = new Fred(), does the Fred memory "leak" if the Fred
constructor
throws an exception?
38. What if I forget the [] when deleteing array allocated via new
T[n]?
39. After p = new Fred[n], how does the compiler know there are n
objects to
be destructed during delete[] p?
40. How can I force objects of my class to always be created via new
rather
than as locals or global/static objects?
41. How do I provide reference counting with copy-on-write semantics
for a
hierarchy of classes?
42. Does garbage collection cause my program's execution to pause?
43. What do you mean, garbage collection and C?
44. What does a garbage collector do about destructors?
45. How should I handle resources if my constructors may throw
exceptions?
46. How do I change the string-length of an array of char to prevent
memory
leaks even if/when someone throws an exception?
47. What is "const correctness"?
48. What's the difference between "const Fred* p", "Fred* const p" and
"const Fred* const p"?
49. What does "Fred const& x" mean?
50. What is a "const member function"?
51. What's the relationship between a return-by-reference and a const
member
function?
52. What's the deal with "const-overloading"?
53. What do I do if I want a const member function to make an
"invisible"
change to a data member?
54. Does const_cast mean lost optimization opportunities?
55. ] Why does the compiler allow me to change an int after I've
pointed at
it with a const int*?
56. Does "const Fred* p" mean that *p can't change?
57. What is a "virtual member function"?
58. ] How can C++ achieve dynamic binding yet also static typing?
59. What's the difference between how virtual and non-virtual member
functions are called?
60. ] What happens in the hardware when I call a virtual function?
How many
layers of indirection are there? How much overhead is there?
61. I have a heterogeneous list of objects, and my code needs to do
class-specific things to the objects. Seems like this ought to use
dynamic binding but can't figure it out. What should I do?
62. ] When should my destructor be virtual?
63. What is a "virtual constructor"?
64. What's the big deal of separating interface from implementation?
65. What is an ABC?An abstract base class.
66. How do you define a copy constructor or assignment operator for a
class
that contains a pointer to a (abstract) base class?
67. Is it okay for a non-virtual function of the base class to call a
virtual function?
68. What does it mean that the "virtual table" is an unresolved
external?
69. ] How can I set up my member function so it won't be overridden
in a
derived class?

70. virtual inheritance?


71. What are the units of sizeof?
72. When initializing non-static data members of built-in / intrinsic
/
primitive types, should I use the "initialization list" or assignment?
73. Can I define an operator overload that works with built-in /
intrinsic /
primitive types?
74. How can I tell if an integer is a power of two without looping?
return i
> 0 && (i & (i - 1)) == 0;

· What does it mean to declare a function or variable as static?


· What is the order of initalization for data?
· What is name mangling/name decoration?
o What kind of problems does name mangling cause?
o How do you work around them?
· What is a class?
o What are the differences between a struct and a class in C++?
o What is the difference between public, private, and protected
access?
o For class CFoo { }; what default methods will the compiler
generate for
you>?
o How can you force the compiler to not generate them?
o What is the purpose of a constructor? Destructor?
o What is a constructor initializer list?
o When must you use a constructor initializer list?
o What is a:
§ Constructor?
§ Destructor?
§ Default constructor?
§ Copy constructor?
§ Conversion constructor?
o What does it mean to declare a...
§ member function as virtual?
§ member function as static?
§ member function as static?
§ member variable as static?
§ destructor as static?
o Can you explain the term "resource acquisition is initialization?"
o What is a "pure virtual" member function?
o What is the difference between public, private, and protected
inheritance?
o What is virtual inheritance?
o What is placement new?
o What is the difference between operator new and the new operator?
What are the major differences between C and C++?
o o What are the differences between new and malloc?
o o What is the difference between delete and delete[]?
o o What are the differences between a struct in C and in
C++?
o o What are the advantages/disadvantages of using #define?
o o What are the advantages/disadvantages of using inline
and const?

What is virtual constructors/destructors? Added: 10/22/2004

C++
Category:
View
s:
1162
7

Rating: (4.0)
By:
37
users

Answer:
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 all
derived-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 and multiple 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<<endl;
}
CoolInterview.com
What do you mean by inline function? Added: 10/22/2004
Question:

C++
Category: Views: 4436

(3.5)
By: 17 users
Rating:

The idea behind inline functions is to insert the code of a called function at the point where
Answer: 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.
CoolInterview.com

Difference between realloc() and free()? Added: 10/22/2004


Question:

C++
Category: Views: 6297

(4.6)
By: 10 users
Rating:

The free subroutine frees a block of memory previously allocated by the malloc subroutine.
Answer: 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 deallocated with the free
or
realloc subroutines. Undefined results occur if the Pointer parameter is not a valid pointer.
CoolInterview.com

What is a template? Added: 10/22/2004


Question:

C++
Category: Views: 4632

(3.1)
By: 7 users
Rating:

Templates allow to create generic functions that admit any data type as parameters and
Answer: 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 <class indetifier> function_declaration; template <typename indetifier>


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.
CoolInterview.com
What is the difference between class and structure? Added: 10/22/2004
Question:

C++
Category: Views: 2303

(4.6)
By: 8 users
Rating:

Structure: Initially (in C) a structure was used to bundle different type of data types together
Answer: 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.
CoolInterview.com

What is RTTI? Added: 10/22/2004


Question:

C++
Category: Views: 5952

(3.2)
By: 6 users
Rating:

Runtime type identification (RTTI) lets you find the dynamic type of an object when you have
Answer: 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.
CoolInterview.com

What is encapsulation? Added: 10/22/2004


Question:

C++
Category: Views: 4283

(2.8)
By: 12 users
Rating:

Packaging an object’s variables within its methods is called encapsulation.


Answer: CoolInterview.com

What is an object? Added: 10/22/2004


Question:

C++
Category: Views: 1683

(3.0)
By: 5 users
Rating:

Object is a software bundle of variables and related methods. Objects have state and behavior.
Answer: CoolInterview.com
What is public, protected, private? Added: 10/22/2004
Question:

C++
Category: Views: 1508

(2.5)
By: 2 users
Rating:

Ø Public, protected and private are three access specifiers in C++.


Answer:
Ø 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.
CoolInterview.com

What is namespace? Added: 10/22/2004


Question:

C++
Category: Views: 5788

(3.3)
By: 15 users
Rating:

Namespaces allow us to group a set of global classes, objects and/or functions under a name.
Answer: 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::a 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.
What do you mean by inheritance? Added: 10/22/2004
Question:

C++
Category: Views: 2000

(4.7)
By: 3 users
Rating:

Inheritance is the process of creating new classes, called derived classes, from existing
Answer: classes or
base classes. The derived class inherits all the capabilities of the base class, but can add
embellishments and refinements of its own.
CoolInterview.com

What is function overloading and operator Added: 10/22/2004


Question: overloading?

C++
Category: Views: 3497

(4.0)
By: 6 users
Rating:

Function overloading: C++ enables several functions of the same name to be defined, as long
Answer: 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).
CoolInterview.com

What is virtual class and friend class? Added: 10/22/2004


Question:

C++
Category: Views: 4279

(1.6)
By: 8 users
Rating:

Friend classes are used when two or more classes are designed to work together and need
Answer: 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 DatabaseCursor to have more privilege to the internals of class Database
than main() has.
CoolInterview.com
What do you mean by binding of data and functions? Added: 10/22/2004
Question:

C++
Category: Views: 3828

(4.0)
By: 5 users
Rating:

Encapsulation.
Answer: CoolInterview.com

What is the difference between an object and a Added: 10/22/2004


Question: class?

C++
Category: Views: 6510

(3.5)
By: 14 users
Rating:

Classes and objects are separate but related concepts. Every object belongs to a class and
Answer: 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 the
execution 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 eventually
destroyed.
Also during that lifetime, the attributes of the object may undergo significant change.
CoolInterview.com

What is a class? Added: 10/22/2004


Question:

C++
Category: Views: 1972

(2.7)
By: 3 users
Rating:

Class is a user-defined data type in C++. It can be created to solve a particular kind of
Answer: problem.
After creation the user need not know the specifics of the working of a class.
CoolInterview.com
What is friend function? Added: 10/22/2004
Question:

C++
Category: Views: 1255

(5.0)
By: 1 users
Rating:

As the name suggests, the function acts as a friend to a class. As a friend of a class, it can
Answer: 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.
CoolInterview.com

What is abstraction? Added: 10/22/2004


Question:

C++
Category: Views: 2512

(4.5)
By: 2 users
Rating:

Abstraction is of the process of hiding unwanted details from the user.


Answer: CoolInterview.com

What are virtual functions? Added: 10/22/2004


Question:

C++
Category: Views: 1851

(5.0)
By: 1 users
Rating:

A virtual function allows derived classes to replace the implementation provided by the base
Answer: 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.
CoolInterview.com

What is a scope resolution operator? Added: 10/22/2004


Question:

C++
Category: Views: 2482

(3.1)
By: 8 users
Rating:

A scope resolution operator (::), can be used to define the member functions of a class
Answer: outside the
class.
What do you mean by pure virtual functions? Added: 10/22/2004
Question:

C++
Category: Views: 5740

(3.7)
By: 11 users
Rating:

A pure virtual member function is a member function that the base class forces derived
Answer: classes to
provide. Normally these member functions have no implementation. Pure virtual functions are
equated to zero.
class Shape { public: virtual void draw() = 0; };
CoolInterview.com

What is polymorphism? Explain with an example? Added: 10/22/2004


Question:

C++
Category: Views: 2611

(3.3)
By: 4 users
Rating:

"Poly" means "many" and "morph" means "form". Polymorphism is the ability of an object (or
Answer: 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.

What is the difference between delete and delete[]?


Whenever you allocate memory with 'new[]', you have to free the memory using
'delete[]'. When you allocate memory with 'new', then use 'delete' without the brackets.
You use 'new[]' to allocate an array of values (always starting at the index 0).

int *pi = new int; // allocates a single integer


int *pi_array = new int[10]; // allocates an array of 10 integers
delete pi;
pi = 0;
delete [] pi_array;
pi_array = 0;
What are the differences between new and malloc?
Operators new and delete
Memory can be allocated and release dynamically by using the functions malloc() and
free() found in <cstdlib>. Memory can also be dynamically managed by the use of the
new and delete keywords in C++. Technically these are operators (Yes, they can be
overloaded).

Important Point

Nothing needs to be included to use new and delete.

There are nice syntactic differences between malloc() and new and between free() and
delete. But the most important differences are in their behavior. The malloc() function
allocates the requested number of bytes and returns a pointer to them. Nothing more. But
after allocating memory for an instance of a class, the new operator will automatically call
the constructor for that class to initialize that section of memory.

Important Point

The main difference between malloc() and new is that new calls a class
constructor after allocating the memory.

Likewise, free() and delete both return memory previously allocated to the system.

Important Point

The main difference between delete and free() is that delete calls the
class destructor method before returning the memory to the system.

The new operator can be used to dynamically allocate arrays (so can malloc()):

Widget *ar;

int n; // Get this value at runtime

ar = new Widget[n];

...

The new operator will allocate the memory for the entire array and then call the default
Widget constructor on each element in the array in order to initialize it.
The delete operator has two forms one for simple instances, one for arrays.

Data *d, *ar;

...

d = new Data;

e = new Data[n];

...

delete d;

delete [] e;

When using delete [], the class destructor will be called on every element of the array
to clean up the array before the memory is returned to the system.

Important Point

The delete [] form should be used when freeing up arrays.

Important Point

The delete form should be used for single instances.

Mixing up the delete and delete [] operators will not cause compile time errors. Very
subtle errors will crop up at runtime in large projects which can be very difficult to track
down.

Answer
both malloc and new functions are used for dynamic memory allocations and the basic
difference is: malloc requires a special "typecasting" when it allocates memory for eg. if
the pointer used is the char pointer then after the processor allocates memory then this
allocated memory needs to be typecasted to char pointer i.e (char*).but new does not
requires any typecasting. Also, free is the keyword used to free the memory while using
malloc and delete the keyword to free memory while using new, otherwise this will lead
the memory leak.
[edit answer]
Answer
Besides the basic syntactical difference: malloc is a C function which will allocate the
amount of memory you ask and thats it. new is a C++ operator which will allocate
memory AND call the constructor of the class for which's object memory is being
allocated.

Similarily, free is a C function which will free up the memory allocated. but delete is a
C++ operator which will free up the allocated memory AND call the destructor of the
object.
[edit answer]

Answer
malloc in a function and new is an operator, and its a good programming practice to use
an operator instead of functions, because function itself requires some time to be
executed whenever that particular function is called. so the main difference is that we use
operators instead of malloc because of the TIME CONSTRAINT.

What are the differences between a struct in C and in C++?

In C, a common style of usage is to say:

struct A {
int x;
};
typedef struct A A;

after which A can be used as a type name to declare objects:

void f()
{
A a;
}

In C++, classes, structs, unions, and enum names are automatically type names, so you
can say:

struct A {
int x;
};
void f()
{
A a;
}
or:

enum E {ee};
void f()
{
E e;
}

By using the typedef trick, you can follow a style of programming in C somewhat like
that used in C++.

But there is a quirk or two when using C++. Consider usage like:

struct A {
int x;
};
int A;
void f()
{
A a;
}

This is illegal because the int declaration A hides the struct declaration. The struct A
can still be used, however, by specifying it via an "elaborated type specifier":

struct A

The same applies to other type names:

class A a;
union U u;
enum E e;

Taking advantage of this feature, that is, giving a class type and a variable or function the
same name, isn't very good usage. It's supported for compatibility reasons with old C
code; C puts structure tags (names) into a separate namespace, but C++ does not. Terms
like "struct compatibility hack" and "1.5 namespace rule" are sometimes used to describe
this feature.

C Interview Questions

Question Difference between arrays and pointers?


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

Question Are pointers integers


Answer pointers are not integers. A pointer is an address. It is merely a positive number
and not an integer.

Question How are pointer variables


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

Question What are the advantages of the


Answer 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
Functions are helpful in generalizing the Program

Question What is a pointer value and Address ?


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

Question What is a pointer variable?


Answer A pointer variable is a variable that may contain the address of another variable
or any valid address in the memory.

Question What is static memory allocation and dynamic memory allocation?


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

Question What is the purpose of main( )


Answer 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

Question What is the purpose of realloc( )?


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

Question What are the advantages of auto variables?


Answer1)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

What is an argument? Differentiate between formal arguments and actual


arguments
Answer An argument is an entity used to pass the data from calling funtion to the called
funtion. Formal arguments are the arguments available in

Question Differentiate between an internal static and external static variable?


Answer An internal static variable is declared inside a block with static storage class
whereas an external static variable is declared outside all the blocks in a file. An internal
static variable has persistent storage, block scope and no linkage. An external static
variable has permanent storage, file scope and internal linkage. the function definition.
They are preceded by their own data types. Actual arguments are
available in the function call.

Question What are advantages and disadvantages of external storage class?


Answer Advantages of external storage class
1)Persistent storage of a variable retains the latest value
2)The value is globally available
Disadvantages of external storage class
1)The storage for an external variable exists even when the variable is not needed
2)The side effect may produce surprising output

Question What is storage class and what are storage variable ?


Answer A storage class is an attribute that changes the behavior of a variable. It controls
the lifetime, scope and linkage. There are five types of storage classes
1) auto
2) static
3) extern
4) register
5) typedef
Question What are the characteristics of arrays in C?
Answer1) An array holds elements that have the same data type
2) Array elements are stored in subsequent memory locations
3) Two-dimensional array elements are stored row by row in subsequent memory
locations.
4) Array name represents the address of the starting element
5) Array size should be mentioned in the declaration. Array size must be a constant
expression and not a variable.

Question Differentiate between a linker and linkage?


Answer A linker converts an object code into an executable code by linking together the
necessary build in functions. The form and place of declaration where the variable is
declared in a program determine the linkage of variable

Question What is a function and built-in function?


Answer A large program is subdivided into a number of smaller programs or
subprograms. Each subprogram specifies one or more actions to be performed for a
large program. such subprograms are functions. The function supports only static and
extern storage classes. By default, function assumes extern storage class. functions have
global scope. Only register or auto storage class is allowed in the function parameters.
Built-in functions that predefined and supplied along with the compiler are known as
built-in functions. They are also known as library functions.

Question When does the compiler not implicitly generate the address of the first
element of an array?
Answer Whenever an array name appears in an expression such as
array as an operand of the sizeof operator
array as an operand of & operator

Question Is it better to use a pointer to navigate an array of values, or is it better to


use a subscripted array name?
Answer It’s easier for a C compiler to generate good code for pointers than for subscripts.
array as a string literal initializer for a character array Then the compiler does not
implicitly generate the address of the address of the first element of an array.

Question why n++ executes faster than n+1?


Answer The expression n++ requires a single machine instruction such as INR to carry
out the increment operation whereas, n+1 requires more

Question Which expression always return true? Which always return false?
Answer expression if (a=0) always return false expression if (a=1) always return true
instructions to carry out this operation.

Question Is it possible to execute code even after the program exits the main()
function?
Answer The standard C library provides a function named atexit() that can be used to
perform “cleanup” operations when your program terminates. You can set up a set of
functions you want to perform automatically when your program exits by passing
function pointers to the at exit() function.

Question What is the difference between a string and an array?


Answer An array is an array of anything. A string is a specific kind of an array with a
well-known convention to determine its length. There are two kinds of programming
languages: those in which a string is just an array of characters, and those in which it’s a
special type. In C, a string is just an array of characters (type char), with one wrinkle: a
C string always ends with a NUL character. The “value” of an array is the same as the
address of (or a pointer to) the first element; so, frequently, a C string and a pointer to
char are used to mean the same thing. An array can be any length. If it’s passed to a
function, there’s no way the function can tell how long the array is supposed to be,
unless some convention is used. The convention for strings is NUL termination; the last
character is an ASCII NUL (‘’) character.

Question What is a static function?


Answer A static function is a function whose scope is limited to the current source file.
Scope refers to the visibility of a function or variable. If the function or variable is visible
outside of the current source file, it is said to have global, or external, scope. If the
function or variable is not visible outside of the current source file, it is said to have
local, or static, scope.

Question what is a modulus operator? What are the restrictions of a modulus


operator?
Answer A Modulus operator gives the remainder value. The result of x%y is obtained by
(x-(x/y)*y). This operator is applied only to integral operands and cannot be applied to
float or double.

Question Is using exit() the same as using return?


Answer The exit() function is used to exit your program and return control to the
operating system. The return statement is used to return from a function and return
control to the calling function. If you issue a return from the main() function, you are
essentially returning control to the calling function, which is the operating system. In this
case, the return statement and exit() function are similar.

Question Write the equivalent expression for x%8?


Answerx&7

Question Can the sizeof operator be used to tell the size of an array passed to a
function?
Answer There’s no way to tell, at runtime, how many elements are in an array parameter
just by looking at the array parameter itself. Remember, passing an array to a function is
exactly the same as passing a pointer to the first element.
Question What is the heap?
Answer The heap is where malloc(), calloc(), and realloc() get memory. Getting memory
from the heap is much slower than getting it from the stack. On the other hand, the heap
is much more flexible than the stack. Memory can be allocated at any time and
deallocated in any order. Such memory isn’t deallocated automatically; you have to call
free(). Recursive data structures are almost always implemented with memory from the
heap. Strings often come from there too, especially strings that could be very long at
runtime. If you can keep data in a local variable (and allocate it from the stack), your
code will run faster than if you put the data on the heap. Sometimes you can use a better
algorithm if you use the heap—faster, or more robust, or more flexible. It’s a tradeoff.
If memory is allocated from the heap, it’s available until the program ends. That’s great
if you remember to deallocate it when you’re done. If you forget, it’s a problem. A
“memory leak” is some allocated memory that’s no longer needed but isn’t deallocated.
If you have a memory leak inside a loop, you can use up all the memory on the heap and
not be able to get any more. (When that happens, the allocation functions return a null
pointer.) In some environments, if a program doesn’t deallocate everything it allocated,
memory stays unavailable even after the program ends.

Question When should a far pointer be used?


Answer Sometimes you can get away with using a small memory model in most of a
given program. There might be just a few things that don’t fit in your small data and code
segments. When that happens, you can use explicit far pointers and function declarations
to get at the rest of memory. A far function can be outside the 64KB segment most
functions are shoehorned into for a small-code model. (Often, libraries are declared
explicitly far, so they’ll work no matter what code model the program uses.)
A far pointer can refer to information outside the 64KB data segment. Typically, such
pointers are used with farmalloc() and such, to manage a heap separate from where all the
rest of the data lives. If you use a small-data, large-code model, you should explicitly
make your function pointers far.

Question What is the stack?


Answer The stack is where all the functions’ local (auto) variables are created. The stack
also contains some information used to call and return from functions. A “stack trace” is a
list of which functions have been called, based on this information. When you start using
a debugger, one of the first things you should learn is how to get a stack trace.
The stack is very inflexible about allocating memory; everything must be deallocated in
exactly the reverse order it was allocated in. For implementing function calls, that is all
that’s needed. Allocating memory off the stack is extremely efficient. One of the reasons
C compilers generate such good code is their heavy use of a simple stack. There used to
be a C function that any programmer could use for allocating memory off the stack. The
memory was automatically deallocated when the calling function returned. This was a
dangerous function to call; it’s not available anymore.

Question What is the difference between NULL and NUL?


Answer NULL is a macro defined in for the null pointer. NUL is the name of the first
character in the ASCII character set. It corresponds to a zero value. There’s no standard
macro NUL in C, but some people like to define it. The digit 0 corresponds to a value of
80, decimal. Don’t confuse the digit 0 with the value of ‘’ (NUL)!
NULL can be defined as ((void*)0), NUL as ‘’.

Question Why should I prototype a function?


Answer A function prototype tells the compiler what kind of arguments a function is
looking to receive and what kind of return value a function is going to give back. This
approach helps the compiler ensure that calls to a function are made correctly and
that no erroneous type conversions are taking place.

Question How do you print an address?


Answer 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 );

Question Can math operations be performed on a void pointer?


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

Question How can you determine the size of an allocated portion of memory?
Answer 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.

Question What is a “null pointer assignment” error? What are bus errors, memory
faults, and core dumps?
Answer These are all serious errors, symptoms of a wild pointer or subscript. Null pointer
assignment is a message you might get when an MS-DOS program finishes executing.
Some such programs can arrange for a small amount of memory to be available “where
the NULL pointer points to” (so to speak). If the program tries to write to that area, it
will overwrite the data put there by the compiler. When the program is done, code
generated by the compiler examines that area. If that data has been changed, the
compiler-generated code complains with null pointer assignment. This message carries
only enough information to get you worried. There’s no way to tell, just
from a null pointer assignment message, what part of your program is responsible for the
error. Some debuggers, and some compilers, can give you more help in finding the
problem. Bus error: core dumped and Memory fault: core dumped are messages you
might see from a program running under UNIX. They’re more programmer
friendly. Both mean that a pointer or an array subscript was wildly out of bounds. You
can get these messages on a read or on a write. They aren’t restricted to null pointer
problems. The core dumped part of the message is telling you about a file, called core,
that has just been written in your current directory. This is a dump of everything on the
stack and in the heap at the time the program was running. With the help of a debugger,
you can use the core dump to find where the bad pointer was used. That might not tell
you why the pointer was bad, but it’s a step in the right direction. If you don’t have write
permission in the current directory, you won’t get a core file, or the core dumped
message.

Question What is a null pointer?


Answer 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

Question What is a void pointer?


Answer A void pointer is a C convention for “a raw address.” The compiler has no idea
what type of object a void Pointer “really points to.” If you write
int *ip; ip points to an int. If you write
void *p; p doesn’t point to a void!
In C and C++, any time you need a void pointer, you can use another pointer type. For
example, if you have a char*, you can pass it to a function that expects a void*. You don’t
even need to cast it. In C (but not in C++), you can use a void* any time you need any
kind of pointer, without casting. (In C++, you need to cast it). A void pointer is used for
working with raw memory or for passing a pointer to an unspecified type. Some C code
operates on raw memory. When C was first invented, character pointers (char *) were
used for that. Then people started getting confused about when a character pointer was a
string, when it was a character array, and when it was raw memory.

Question Is NULL always defined as 0?


Answer 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, as
Necessary, whenever a pointer is needed (although the compiler can’t always tell when a
pointer is needed).

Question What does it mean when a pointer is used in an if statement?


Answer Any time a pointer is used as a condition, it means “Is this a non-null pointer?” A
pointer can be used in an if, while, for, or do/while statement, or in a conditional
expression.
Question How do you use a pointer to a function?
Answer The hardest part about using a pointer-to-function is declaring it. Consider an
example. You want to create a pointer, pf, that points to the strcmp() function. The
strcmp() function is declared in this way: int strcmp(const char *, const char * )
To set up pf to point to the strcmp() function, you want a declaration that looks just like
the strcmp() function’s declaration, but that has *pf rather than strcmp: int (*pf)( const
char *, const char * ); After you’ve gotten the declaration of pf, you can #include and
assign the address of strcmp() to pf: pf = strcmp;

Question Why should we assign NULL to the elements (pointer) after freeing them?
Answer This is paranoia based on long experience. After a pointer has been freed, you
can no longer use the pointed-to data. The pointer is said to “dangle”; it doesn’t point at
anything useful. If you “NULL out” or “zero out” a pointer immediately after freeing it,
your program can no longer get in trouble by using that pointer. True, you might go
indirect on the null pointer instead, but that’s something your debugger might be able to
help you with immediately. Also, there still might be copies of the pointer that refer
to the memory that has been deallocated; that’s the nature of C. Zeroing out pointers after
freeing them won’t solve all problems;

Question When would you use a pointer to a function?


Answer Pointers to functions are interesting when you pass them to other functions. A
function that takes function pointers says, in effect, “Part of what I do can be customized.
Give me a pointer to a function, and I’ll call it when that part of the job needs to be done.
That function can do its part for me.” This is known as a “callback.” It’s used a lot in
graphical user interface libraries, in which the style of a display is built into the library
but the contents of the display are part of the application. As a simpler example, say you
have an array of character pointers (char*s), and you want to sort it by the value of the
strings the character pointers point to. The standard qsort() function uses function
pointers to perform that task. qsort() takes four arguments,
a pointer to the beginning of the array,
the number of elements in the array,
the size of each array element, and
a comparison function, and returns an int.

Question Is it better to use malloc() or calloc()?


Answer Both the malloc() and the calloc() functions are used to allocate dynamic
memory. Each operates slightly different from the other. malloc() takes a size and returns
a pointer to a chunk of memory at least that big: void *malloc( size_t size );
calloc() takes a number of elements, and the size of each, and returns a pointer to a chunk
of memory at least big enough to hold them all: void *calloc( size_t numElements, size_t
sizeOfElement ); There’s one major difference and one minor difference between the two
functions. The major difference is that malloc() doesn’t initialize the allocated memory.
The first time malloc() gives you a particular chunk of memory, the memory might be
full of zeros. If memory has been allocated, freed, and reallocated, it probably has
whatever junk was left in it. That means, unfortunately, that a program might run
in simple cases (when memory is never reallocated) but break when used harder (and
when memory is reused). calloc() fills the allocated memory with all zero bits. That
means that anything there you’re going to use as a char or an int of any length, signed or
unsigned, is guaranteed to be zero. Anything you’re going to use as a pointer is set to all
zero bits. That’s usually a null pointer, but it’s not guaranteed.Anything you’re going to
use as a float or double is set to all zero bits; that’s a floating-point zero on some types of
machines, but not on all. The minor difference between the two is that calloc() returns an
array of objects; malloc() returns one object. Some people use calloc() to make clear that
they want an array.

Question What is the benefit of using an enum rather than a #define constant?
Answer The use of an enumeration constant (enum) has many advantages over using the
traditional symbolic constant style of #define. These advantages include a lower
maintenance requirement, improved program readability, and better debugging capability.
1) The first advantage is that enumerated constants are generated automatically by the
compiler. Conversely, symbolic constants must be manually assigned values by the
programmer. For instance, if you had an enumerated constant type for error codes that
could occur in your program, your enum definition could look something like this:
enum Error_Code
{
OUT_OF_MEMORY,
INSUFFICIENT_DISK_SPACE,
LOGIC_ERROR,
FILE_NOT_FOUND
};
In the preceding example, OUT_OF_MEMORY is automatically assigned the value of 0
(zero) by the compiler because it appears first in the definition. The compiler then
continues to automatically assign numbers to the enumerated constants, making
INSUFFICIENT_DISK_SPACE equal to 1, LOGIC_ERROR equal to 2, and
FILE_NOT_FOUND equal to 3, so on. If you were to approach the same example by
using symbolic constants, your code would look something like this:

#define OUT_OF_MEMORY 0
#define INSUFFICIENT_DISK_SPACE 1
#define LOGIC_ERROR 2
#define FILE_NOT_FOUND 3

values by the programmer. Each of the two methods arrives at the same result: four
constants assigned numeric values to represent error codes. Consider the maintenance
required, however, if you were to add two constants to represent the error codes
DRIVE_NOT_READY and CORRUPT_FILE. Using the enumeration constant
method, you simply would put these two constants anywhere in the enum definition. The
compiler would generate two unique values for these constants. Using the symbolic
constant method, you would have to manually assign two new numbers to these
constants. Additionally, you would want to ensure that the numbers you assign to these
constants are unique.
2) Another advantage of using the enumeration constant method is that your programs are
more readable and thus can be understood better by others who might have to update
your program later.
3) A third advantage to using enumeration constants is that some symbolic debuggers can
print the value of an enumeration constant. Conversely, most symbolic debuggers cannot
print the value of a symbolic constant. This can be an enormous help in debugging your
program, because if your program is stopped at a line that uses an enum, you can simply
inspect that constant and instantly know its value. On the other hand, because most
debuggers cannot print #define values, you would most likely have to search for
that value by manually looking it up in a header file.

Question How are portions of a program disabled in demo versions?


Answer If you are distributing a demo version of your program, the preprocessor can be
used to enable or disable portions of your program. The following portion of code shows
how this task is accomplished, using the preprocessor directives #if and #endif:
int save_document(char* doc_name)
{
#if DEMO_VERSION
printf(“Sorry! You can’t save documents using
the DEMO version of this program!n”);
return(0);
#endif
...
}

Question What is the difference between #include <file> and #include “file”?
Answer When writing your C program, you can include files in two ways. The first way
is to surround the file you want to include with the angled brackets < and >. This method
of inclusion tells the preprocessor to look for the file in the predefined default location.
This predefined default location is often an INCLUDE environment variable that denotes
the path to your include files. For instance, given the INCLUDE variable
INCLUDE=C:\COMPILER\INCLUDE;S:\SOURCE\HEADERS;
using the #include version of file inclusion, the compiler first checks the
C:\COMPILER\INCLUDE
directory for the specified file. If the file is not found there, the compiler then checks the
S:\SOURCE\HEADERS directory. If the file is still not found, the preprocessor checks
the current directory. The second way to include files is to surround the file you want to
include with double quotation marks. This method of inclusion tells the preprocessor to
look for the file in the current directory first, then look for it in the predefined locations
you have set up. Using the #include “file” version of file inclusion and applying it to the
preceding example, the preprocessor first checks the current directory for the specified
file. If the file is not found in the current directory, the C:COMPILERINCLUDE
directory is searched. If the file is still not found, the preprocessor checks the
S:SOURCEHEADERS directory. The #include method of file inclusion is often
used to include standard headers such as stdio.h or stdlib.h. This is because these
headers are rarely (if ever) modified, and they should always be read from your
compiler’s standard include file directory.
The #include “file” method of file inclusion is often used to include nonstandard header
files that you have created for use in your program. This is because these headers are
often modified in the current directory, and you will want the preprocessor to use your
newly modified version of the header rather than the older, unmodified version.
Question How many levels of pointers can you have?
Answer The answer depends on what you mean by “levels of pointers.” If you mean
“How many levels of indirection can you have in a single declaration?” the answer is “At
least 12.”
int i = 0;
int *ip01 = & i;
int **ip02 = & ip01;
int ***ip03 = & ip02;
int ****ip04 = & ip03;
int *****ip05 = & ip04;
int ******ip06 = & ip05;
int *******ip07 = & ip06;
int ********ip08 = & ip07;
int *********ip09 = & ip08;
int **********ip10 = & ip09;
int ***********ip11 = & ip10;
int ************ip12 = & ip11;
************ip12 = 1; /* i = 1 */
The ANSI C standard says all compilers must handle at least 12 levels. Your compiler
might support more.

Question How can I convert a string to a number?


Answer The standard C library provides several functions for converting strings to
numbers of all formats (integers, longs, floats, and so on) and vice versa.
The following functions can be used to convert strings to numbers:
Function Name Purpose atof() Converts a string to a double-precision
floating-point value. atoi() Converts a string to an integer. atol() Converts a string to a
long integer. strtod() Converts a string to a double-precision floating-point value and
reports any “leftover” numbers that could not be converted. strtol() Converts a string to a
long integer and reports any “leftover” numbers that could not be converted. strtoul()
Converts a string to an unsigned long integer and reports any “leftover” numbers that
could not be converted.

Question How do you print only part of a string?


Answer/* Use printf() to print the first 11 characters of source_str. */
printf(“First 11 characters: ‘%11.11s’n”, source_str);

Question What is the difference between a string copy (strcpy) and a memory copy
(memcpy)? When should each be us
Answer The strcpy() function is designed to work exclusively with strings. It copies each
byte of the source string to the destination string and stops when the terminating null
character () has been moved. On the other hand, the memcpy() function is designed to
work with any type of data. Because not all data ends with a null character, you must
provide the memcpy() function with the number of bytes you want to copy from the
source to the destination.
Question What is a pragma?
Answer The #pragma preprocessor directive allows each compiler to implement
compiler-specific features that can be turned on and off with the #pragma statement. For
instance, your compiler might support a feature called loop optimization. This feature can
be invoked as a command-line option or as a #pragma directive. To implement this option
using the #pragma directive, you would put the following line into your code:
#pragma loop_opt(on)
Conversely, you can turn off loop optimization by inserting the following line into your
code:
#pragma loop_opt(off)

Question How can I convert a number to a string?


Answer The standard C library provides several functions for converting numbers of all
formats (integers, longs, floats, and so on) to strings and vice versa The following
functions can be used to convert integers to strings: Function Name Purpose
itoa() Converts an integer value to a string. ltoa() Converts a long integer value to a
string. ultoa() Converts an unsigned long integer value to a string. The following
functions can be used to convert floating-point values to strings:
Function Name Purpose ecvt() Converts a double-precision floating-point value to a
string without an embedded decimal point. fcvt() Same as ecvt(), but forces the precision
to a specified number of digits. gcvt() Converts a double-precision floating-point value
to a string with an embedded decimal point.

Question Is it better to use a macro or a function?


Answer The answer depends on the situation you are writing code for. Macros have the
distinct advantage of being more efficient (and faster) than functions, because their
corresponding code is inserted directly into your source code at the point where the
macro is called. There is no overhead involved in using a macro like there is in placing a
call to a function. However, macros are generally small and cannot handle large, complex
coding constructs. A function is more suited for this type of situation. Additionally,
macros are expanded inline, which means that the code is replicated for each occurrence
of a macro. Your code therefore could be somewhat larger when you use macros than if
you were to use functions. Thus, the choice between using a macro and using a function
is one of deciding between the tradeoff of faster program speed versus smaller program
size. Generally, you should use macros to replace small, repeatable code sections, and
you should use functions for larger coding tasks that might require several lines of code.

Question How do you override a defined macro?


Answer You can use the #undef preprocessor directive to undefine (override) a previously
defined macro.

Question What are the standard predefined macros?


Answer The ANSI C standard defines six predefined macros for use in the C language:
Macro Name Purpose
_ _LINE_ _ Inserts the current source code line number in your code.
_ _FILE_ _ Inserts the current source code filename in your code.
_ _DATE_ _ Inserts the current date of compilation in your code.
_ _TIME_ _ Inserts the current time of compilation in your code.
_ _STDC_ _ Is set to 1 if you are enforcing strict ANSI C conformity.
_ _cplusplus Is defined if you are compiling a C++ program.

Question Can you define which header file to include at compile time?
Answer Yes. This can be done by using the #if, #else, and #endif preprocessor directives.
For example, certain compilers use different names for header files. One such case is
between Borland C++, which uses the header file alloc.h, and Microsoft C++,
which uses the header file malloc.h. Both of these headers serve the same purpose, and
each contains roughly the same definitions. If, however, you are writing a program that is
to support Borland C++ and Microsoft C++, you must define which header to include at
compile time. The following example shows how this can be done:
#ifdef _ _BORLANDC_ _
#include
#else
#include
#endif

Question How many levels deep can include files be nested?


Answer Even though there is no limit to the number of levels of nested include files you
can have, your compiler might run out of stack space while trying to include an
inordinately high number of files. This number varies according to your hardware
configuration and possibly your compiler.

Question Can a file other than a .h file be included with #include?


Answer The preprocessor will include whatever file you specify in your #include
statement. Therefore, if you have the line #include in your program, the file macros.inc
will be included in your precompiled program. It is, however, unusual programming
practice to put any file that does not have a .h or .hpp extension in an #include statement.
You should always put a .h extension on any of your C files you are going to include.
This method makes it easier for you and others to identify which files are being used for
preprocessing purposes. For instance, someone modifying or debugging your program
might not know to look at the macros.inc file for macro definitions. That person might try
in vain by searching all files with .h extensions and come up empty. If your file had been
named macros.h, the search would have included the macros.h file, and the searcher
would have been able to see what macros you defined in it.

Question What is Preprocessor?


AnswerThe preprocessor is used to modify your program according to the preprocessor
directives in your source code. Preprocessor directives (such as #define) give the
preprocessor specific instructions on how to modify your source code. The preprocessor
reads in all of your include files and the source code you are compiling and creates a
preprocessed version of your source code. This preprocessed version has all of its macros
and constant symbols replaced by their corresponding code and value assignments. If
your source code contains any conditional preprocessor directives (such as #if), the
preprocessor evaluates the condition and modifies your source code accordingly.
The preprocessor contains many features that are powerful to use, such as creating acros,
performing conditional compilation, inserting predefined environment variables into your
code, and turning compiler features on and off. For the professional programmer, in-
depth knowledge of the features of the preprocessor can be one of the keys to creating
fast, efficient programs.

Question How can you avoid including a header more than once?
Answer One easy technique to avoid multiple inclusions of the same header is to use the
#ifndef and #define preprocessor directives. When you create a header for your program,
you can #define a symbolic name that is unique to that header. You can use the
conditional preprocessor directive named #ifndef to check whether that symbolic name
has already been assigned. If it is assigned, you should not include the header, because it
has already been preprocessed. If it is not defined, you should define it to avoid any
further inclusions of the header. The following header illustrates this technique:

#ifndef _FILENAME_H
#define _FILENAME_H
#define VER_NUM “1.00.00”
#define REL_DATE “08/01/94”
#if _ _WINDOWS_ _
#define OS_VER “WINDOWS”
#else
#define OS_VER “DOS”
#endif
#endif

When the preprocessor encounters this header, it first checks to see whether
_FILENAME_H has been defined. If it hasn’t been defined, the header has not been
included yet, and the _FILENAME_H symbolic name is defined. Then, the rest of the
header is parsed until the last #endif is encountered, signaling the end of the conditional
#ifndef _FILENAME_H statement. Substitute the actual name of the header file
for “FILENAME” in the preceding example to make it applicable for your programs.

Question How can I make sure that my program is the only one accessing a file?
Answer By using the sopen() function you can open a file in shared mode and explicitly
deny reading and writing permissions to any other program but yours. This task is
accomplished by using the SH_DENYWR shared flag to denote that your program is
going to deny any writing or reading attempts by other programs. For example, the
following snippet of code shows a file being opened in shared mode, denying access to
all other files: /* Note that the sopen() function is not ANSI
compliant... */
fileHandle = sopen(“C:DATASETUP.DAT”, O_RDWR,
SH_DENYWR);
By issuing this statement, all other programs are denied access to the SETUP.DAT file. If
another program were to try to open SETUP.DAT for reading or writing, it would receive
an EACCES error code, denoting that access is denied to the file.

Question How can you restore a redirected standard stream?


Answer The preceding example showed how you can redirect a standard stream from
within your program. But what if later in your program you wanted to restore the
standard stream to its original state? By using the standard C library functions named
dup() and fdopen(), you can restore a standard stream such as stdout to its
original state. The dup() function duplicates a file handle. You can use the dup() function
to save the file handle corresponding to the stdout standard stream. The fdopen() function
opens a stream that has been duplicated with the dup() function.

Question What is the quickest searching method to use?


Answer A binary search, such as bsearch() performs, is much faster than a linear search.
A hashing algorithm can provide even faster searching. One particularly interesting and
fast method for searching is to keep the data in a “digital trie.” A digital trie offers the
prospect of being able to search for an item in essentially a constant amount of time,
independent of how many items are in the data set. A digital trie combines aspects of
binary searching, radix searching, and hashing. The term “digital trie” refers to the data
structure used to hold the items to be searched. It is a multilevel data structure that
branches N ways at each level.

Question What is the easiest searching method to use?


Answer Just as qsort() was the easiest sorting method, because it is part of the standard
library, bsearch() is the easiest searching method to use. If the given array is in the sorted
order bsearch() is the best method. Following is the prototype for bsearch():
void *bsearch(const void *key, const void *buf, size_t num, size_t size, int
(*comp)(const void *, const void*));
Another simple searching method is a linear search. A linear search is not as fast as
bsearch() for searching among a large number of items, but it is adequate for many
purposes. A linear search might be the only method available, if the data isn’t sorted or
can’t be accessed randomly. A linear search starts at the beginning and sequentially
compares the key to each element in the data set.

Question What is the easiest sorting method to use?


Answer 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));

Question What is the benefit of using const for declaring constants?


Answer The benefit of using the const keyword is that the compiler might be able to
make optimizations based on the knowledge that the value of the variable will not
change. In addition, the compiler will try to ensure that the values won’t be changed
inadvertently. Of course, the same benefits apply to #defined constants. The reason to use
const rather than #define to define a constant is that a const variable can be of any type
(such as a struct, which can’t be represented by a #defined constant). Also, because a
const variable is a real variable, it has an address that can be used, if needed, and it
resides in only one place in memory

Question Can static variables be declared in a header file?


Answer You can’t declare a static variable without defining it as well (this is because the
storage class modifiers static and extern are mutually exclusive). A static variable can be
defined in a header file, but this would cause each source file that included the header file
to have its own private copy of the variable, which is probably not what was intended.

Question When is a switch statement better than multiple if statements?


Answer A switch statement is generally best to use when you have more than two
conditional expressions based on a single variable of numeric type.

Question when should the volatile modifier be used?


Answer The volatile modifier is a directive to the compiler’s optimizer that operations
involving this variable should not be optimized in certain ways. There are two special
cases in which use of the volatile modifier is desirable. The first case involves memory-
mapped hardware (a device such as a graphics adaptor that appears to the computer’s
hardware as if it were part of the computer’s memory), and the second involves shared
memory (memory used by two or more programs running simultaneously).
Most computers have a set of registers that can be accessed faster than the computer’s
main memory. A good compiler will perform a kind of optimization called “redundant
load and store removal.” The compiler looks for places in the code where it can either
remove an instruction to load data from memory because the value is already in a
register, or remove an instruction to store data to memory because the value can stay in a
register until it is changed again anyway. If a variable is a pointer to something other
than normal memory, such as memory-mapped ports on a peripheral, redundant load and
store optimizations might be detrimental. For instance, here’s a piece of code that might
be used to time some operation:
time_t time_addition(volatile const struct timer
*t, int a)
{
int n;
int x;
time_t then;
x = 0;
then = t->value;
for (n = 0; n < 1000; n++)
{
x = x + a;
}
return t->value - then;
}
this code, the variable t->value is actually a hardware counter that is being incremented
as time passes. The function adds the value of a to x 1000 times, and it returns the amount
the timer was incremented by while the 1000 additions were being performed. Without
the volatile modifier, a clever optimizer might assume that the value of t does not change
during the execution of the function, because there is no statement that explicitly changes
it. In that case, there’s no need to read it from memory a second time and subtract it,
because the answer will always be 0. The compiler might therefore “optimize” the
function by making it always return 0. If a variable points to data in shared memory,
you also don’t want the compiler to perform redundant load and store optimizations.
Shared memory is normally used to enable two programs to communicate with each other
by having one program store data in the shared portion of memory and the other program
read the same portion of memory. If the compiler optimizes away a load or store of
shared memory, communication between the two programs will be affected.
Question What is a const pointer?
AnswerThe access modifier keyword const is a promise the programmer makes to the
compiler that the value of a variable will not be changed after it is initialized. The
compiler will enforce that promise as best it can by not enabling the programmer to write
code which modifies a variable that has been declared const. A “const pointer,” or more
correctly, a “pointer to const,” is a pointer which points to data that is const
(constant, or unchanging). A pointer to const is declared by putting the word const at the
beginning of the pointer declaration. This declares a pointer which points to data that
can’t be modified. The pointer itself can be modified. The following example illustrates
some legal and illegal uses of a const pointer:
const char *str = “hello”;
char c = *str /* legal */
str++; /* legal */
*str = ‘a’; /* illegal */
str[1] = ‘b’; /* illegal */

Question What is the quickest sorting method to use?


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

C++ Interview Questions


Question What is a class?
Answer 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.

Question What is an object?


Answer Object is a software bundle of variables and related methods. Objects have state
and behavior.

Question What is a template?


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

Question What is abstraction?


Answer Abstraction is of the process of hiding unwanted details from the user.

Question What is virtual constructors/ destructors?


Answer 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 all
derived-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 and
multiple 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<}

Question what is the difference between an object and a class?


Answer 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 the
execution 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 eventually
destroyed. Also during that lifetime, the attributes of the object may undergo significant
change.

Question What is the difference between class and structure?


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

Question What is virtual class and friend


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

Question What is polymorphism? Explain with an example?


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

Question What is public, protected, private?


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

Question What is RTTI?


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

Question What is friend function?


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

Question What is function overloading and operator overloading?


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

Question What is namespace?


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

Question What do you mean by inline function?


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

Question What do you mean by pure virtual functions?


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;
};

Question What is a scope resolution operator?


Answer A scope resolution operator (::), can be used to define the member functions of a
class outside the class.
Question Difference between realloc() and free()?
Answer 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 deallocated with the free or realloc subroutines.
Undefined results occur if the Pointer parameter is not a valid pointer.

Question What are virtual functions?


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

Question Explain kill() and its possible return values.


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

Question How many prompts are available in a UNIX system?


Answer Two prompts, PS1 (Primary Prompt), PS2 (Secondary Prompt).

Question How to terminate a process which is running and the specialty on


command kill
0?
Answer With the help of kill command we can terminate the process. Syntax: kill pid
Kill 0 - kills all processes in your system except the login shell.

Question Is it possible to create new a file system in UNIX?


Answer Yes, ‘mkfs’ is used to create a new file system.
Question What are shell variables?
Answer Shell variables are special variables, a name-value pair created and maintained
by the shell. Example: PATH, HOME, MAIL and TERM

Question What daemon is responsible for tracking events on your system?


Answer : syslogd The syslogd daemon is responsible for tracking system information and
saving it to specified log files.

Question What is the name and path of the default configuration file used by the
syslogd
Daemon?
Answer : /etc/syslog.conf If no configuration file is specified when starting syslogd, then
it will start up with the configuration specified in the /etc/syslog.conf file.

Question which command is used to delete all files in the current directory and all
its sub-directories?
Answer rm -r *

Question Write a command to display a file’s contents in various formats?


Answer $od -cbd file_name c - character, b - binary (octal), d-decimal,
od=Octal Dump.

Question Write a command to kill the last background job?


Answer Kill $!

C Interview Questions
Question Difference between arrays and pointers?
Answer 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.

Question Are pointers integers


Answer pointers are not integers. A pointer is an address. It is merely a positive number
and not an integer.

Question How are pointer variables


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

Question What are the advantages of the


Answer 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
Functions are helpful in generalizing the Program

Question What is a pointer value and Address ?


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

Question What is a pointer variable?


Answer A pointer variable is a variable that may contain the address of another variable
or any valid address in the memory.

Question What is static memory allocation and dynamic memory allocation?


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

Question What is the purpose of main( )


Answer 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

Question What is the purpose of realloc( )?


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

Question What are the advantages of auto variables?


Answer1)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

What is an argument? Differentiate between formal arguments and actual


arguments
Answer An argument is an entity used to pass the data from calling funtion to the called
funtion. Formal arguments are the arguments available in

Question Differentiate between an internal static and external static variable?


Answer An internal static variable is declared inside a block with static storage class
whereas an external static variable is declared outside all the blocks in a file. An internal
static variable has persistent storage, block scope and no linkage. An external static
variable has permanent storage, file scope and internal linkage. the function definition.
They are preceded by their own data types. Actual arguments are
available in the function call.

Question What are advantages and disadvantages of external storage class?


Answer Advantages of external storage class
1)Persistent storage of a variable retains the latest value
2)The value is globally available
Disadvantages of external storage class
1)The storage for an external variable exists even when the variable is not needed
2)The side effect may produce surprising output

Question What is storage class and what are storage variable ?


Answer A storage class is an attribute that changes the behavior of a variable. It controls
the lifetime, scope and linkage. There are five types of storage classes
1) auto
2) static
3) extern
4) register
5) typedef

Question What are the characteristics of arrays in C?


Answer1) An array holds elements that have the same data type
2) Array elements are stored in subsequent memory locations
3) Two-dimensional array elements are stored row by row in subsequent memory
locations.
4) Array name represents the address of the starting element
5) Array size should be mentioned in the declaration. Array size must be a constant
expression and not a variable.

Question Differentiate between a linker and linkage?


Answer A linker converts an object code into an executable code by linking together the
necessary build in functions. The form and place of declaration where the variable is
declared in a program determine the linkage of variable

Question What is a function and built-in function?


Answer A large program is subdivided into a number of smaller programs or
subprograms. Each subprogram specifies one or more actions to be performed for a
large program. such subprograms are functions. The function supports only static and
extern storage classes. By default, function assumes extern storage class. functions have
global scope. Only register or auto storage class is allowed in the function parameters.
Built-in functions that predefined and supplied along with the compiler are known as
built-in functions. They are also known as library functions.

Question When does the compiler not implicitly generate the address of the first
element of an array?
Answer Whenever an array name appears in an expression such as
array as an operand of the sizeof operator
array as an operand of & operator

Question Is it better to use a pointer to navigate an array of values, or is it better to


use a subscripted array name?
Answer It’s easier for a C compiler to generate good code for pointers than for subscripts.
array as a string literal initializer for a character array Then the compiler does not
implicitly generate the address of the address of the first element of an array.

Question why n++ executes faster than n+1?


Answer The expression n++ requires a single machine instruction such as INR to carry
out the increment operation whereas, n+1 requires more
Question Which expression always return true? Which always return false?
Answer expression if (a=0) always return false expression if (a=1) always return true
instructions to carry out this operation.

Question Is it possible to execute code even after the program exits the main()
function?
Answer The standard C library provides a function named atexit() that can be used to
perform “cleanup” operations when your program terminates. You can set up a set of
functions you want to perform automatically when your program exits by passing
function pointers to the at exit() function.

Question What is the difference between a string and an array?


Answer An array is an array of anything. A string is a specific kind of an array with a
well-known convention to determine its length. There are two kinds of programming
languages: those in which a string is just an array of characters, and those in which it’s a
special type. In C, a string is just an array of characters (type char), with one wrinkle: a
C string always ends with a NUL character. The “value” of an array is the same as the
address of (or a pointer to) the first element; so, frequently, a C string and a pointer to
char are used to mean the same thing. An array can be any length. If it’s passed to a
function, there’s no way the function can tell how long the array is supposed to be,
unless some convention is used. The convention for strings is NUL termination; the last
character is an ASCII NUL (‘’) character.

Question What is a static function?


Answer A static function is a function whose scope is limited to the current source file.
Scope refers to the visibility of a function or variable. If the function or variable is visible
outside of the current source file, it is said to have global, or external, scope. If the
function or variable is not visible outside of the current source file, it is said to have
local, or static, scope.

Question what is a modulus operator? What are the restrictions of a modulus


operator?
Answer A Modulus operator gives the remainder value. The result of x%y is obtained by
(x-(x/y)*y). This operator is applied only to integral operands and cannot be applied to
float or double.

Question Is using exit() the same as using return?


Answer The exit() function is used to exit your program and return control to the
operating system. The return statement is used to return from a function and return
control to the calling function. If you issue a return from the main() function, you are
essentially returning control to the calling function, which is the operating system. In this
case, the return statement and exit() function are similar.

Question Write the equivalent expression for x%8?


Answerx&7
Question Can the sizeof operator be used to tell the size of an array passed to a
function?
Answer There’s no way to tell, at runtime, how many elements are in an array parameter
just by looking at the array parameter itself. Remember, passing an array to a function is
exactly the same as passing a pointer to the first element.

Question What is the heap?


Answer The heap is where malloc(), calloc(), and realloc() get memory. Getting memory
from the heap is much slower than getting it from the stack. On the other hand, the heap
is much more flexible than the stack. Memory can be allocated at any time and
deallocated in any order. Such memory isn’t deallocated automatically; you have to call
free(). Recursive data structures are almost always implemented with memory from the
heap. Strings often come from there too, especially strings that could be very long at
runtime. If you can keep data in a local variable (and allocate it from the stack), your
code will run faster than if you put the data on the heap. Sometimes you can use a better
algorithm if you use the heap—faster, or more robust, or more flexible. It’s a tradeoff.
If memory is allocated from the heap, it’s available until the program ends. That’s great
if you remember to deallocate it when you’re done. If you forget, it’s a problem. A
“memory leak” is some allocated memory that’s no longer needed but isn’t deallocated.
If you have a memory leak inside a loop, you can use up all the memory on the heap and
not be able to get any more. (When that happens, the allocation functions return a null
pointer.) In some environments, if a program doesn’t deallocate everything it allocated,
memory stays unavailable even after the program ends.

Question When should a far pointer be used?


Answer Sometimes you can get away with using a small memory model in most of a
given program. There might be just a few things that don’t fit in your small data and code
segments. When that happens, you can use explicit far pointers and function declarations
to get at the rest of memory. A far function can be outside the 64KB segment most
functions are shoehorned into for a small-code model. (Often, libraries are declared
explicitly far, so they’ll work no matter what code model the program uses.)
A far pointer can refer to information outside the 64KB data segment. Typically, such
pointers are used with farmalloc() and such, to manage a heap separate from where all the
rest of the data lives. If you use a small-data, large-code model, you should explicitly
make your function pointers far.

Question What is the stack?


Answer The stack is where all the functions’ local (auto) variables are created. The stack
also contains some information used to call and return from functions. A “stack trace” is a
list of which functions have been called, based on this information. When you start using
a debugger, one of the first things you should learn is how to get a stack trace.
The stack is very inflexible about allocating memory; everything must be deallocated in
exactly the reverse order it was allocated in. For implementing function calls, that is all
that’s needed. Allocating memory off the stack is extremely efficient. One of the reasons
C compilers generate such good code is their heavy use of a simple stack. There used to
be a C function that any programmer could use for allocating memory off the stack. The
memory was automatically deallocated when the calling function returned. This was a
dangerous function to call; it’s not available anymore.

Question What is the difference between NULL and NUL?


Answer NULL is a macro defined in for the null pointer. NUL is the name of the first
character in the ASCII character set. It corresponds to a zero value. There’s no standard
macro NUL in C, but some people like to define it. The digit 0 corresponds to a value of
80, decimal. Don’t confuse the digit 0 with the value of ‘’ (NUL)!
NULL can be defined as ((void*)0), NUL as ‘’.

Question Why should I prototype a function?


Answer A function prototype tells the compiler what kind of arguments a function is
looking to receive and what kind of return value a function is going to give back. This
approach helps the compiler ensure that calls to a function are made correctly and
that no erroneous type conversions are taking place.

Question How do you print an address?


Answer 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 );

Question Can math operations be performed on a void pointer?


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

Question How can you determine the size of an allocated portion of memory?
Answer 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.

Question What is a “null pointer assignment” error? What are bus errors, memory
faults, and core dumps?
Answer These are all serious errors, symptoms of a wild pointer or subscript. Null pointer
assignment is a message you might get when an MS-DOS program finishes executing.
Some such programs can arrange for a small amount of memory to be available “where
the NULL pointer points to” (so to speak). If the program tries to write to that area, it
will overwrite the data put there by the compiler. When the program is done, code
generated by the compiler examines that area. If that data has been changed, the
compiler-generated code complains with null pointer assignment. This message carries
only enough information to get you worried. There’s no way to tell, just
from a null pointer assignment message, what part of your program is responsible for the
error. Some debuggers, and some compilers, can give you more help in finding the
problem. Bus error: core dumped and Memory fault: core dumped are messages you
might see from a program running under UNIX. They’re more programmer
friendly. Both mean that a pointer or an array subscript was wildly out of bounds. You
can get these messages on a read or on a write. They aren’t restricted to null pointer
problems. The core dumped part of the message is telling you about a file, called core,
that has just been written in your current directory. This is a dump of everything on the
stack and in the heap at the time the program was running. With the help of a debugger,
you can use the core dump to find where the bad pointer was used. That might not tell
you why the pointer was bad, but it’s a step in the right direction. If you don’t have write
permission in the current directory, you won’t get a core file, or the core dumped
message.

Question What is a null pointer?


Answer 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

Question What is a void pointer?


Answer A void pointer is a C convention for “a raw address.” The compiler has no idea
what type of object a void Pointer “really points to.” If you write
int *ip; ip points to an int. If you write
void *p; p doesn’t point to a void!
In C and C++, any time you need a void pointer, you can use another pointer type. For
example, if you have a char*, you can pass it to a function that expects a void*. You don’t
even need to cast it. In C (but not in C++), you can use a void* any time you need any
kind of pointer, without casting. (In C++, you need to cast it). A void pointer is used for
working with raw memory or for passing a pointer to an unspecified type. Some C code
operates on raw memory. When C was first invented, character pointers (char *) were
used for that. Then people started getting confused about when a character pointer was a
string, when it was a character array, and when it was raw memory.

Question Is NULL always defined as 0?


Answer 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, as
Necessary, whenever a pointer is needed (although the compiler can’t always tell when a
pointer is needed).

Question What does it mean when a pointer is used in an if statement?


Answer Any time a pointer is used as a condition, it means “Is this a non-null pointer?” A
pointer can be used in an if, while, for, or do/while statement, or in a conditional
expression.
Question How do you use a pointer to a function?
Answer The hardest part about using a pointer-to-function is declaring it. Consider an
example. You want to create a pointer, pf, that points to the strcmp() function. The
strcmp() function is declared in this way: int strcmp(const char *, const char * )
To set up pf to point to the strcmp() function, you want a declaration that looks just like
the strcmp() function’s declaration, but that has *pf rather than strcmp: int (*pf)( const
char *, const char * ); After you’ve gotten the declaration of pf, you can #include and
assign the address of strcmp() to pf: pf = strcmp;

Question Why should we assign NULL to the elements (pointer) after freeing them?
Answer This is paranoia based on long experience. After a pointer has been freed, you
can no longer use the pointed-to data. The pointer is said to “dangle”; it doesn’t point at
anything useful. If you “NULL out” or “zero out” a pointer immediately after freeing it,
your program can no longer get in trouble by using that pointer. True, you might go
indirect on the null pointer instead, but that’s something your debugger might be able to
help you with immediately. Also, there still might be copies of the pointer that refer
to the memory that has been deallocated; that’s the nature of C. Zeroing out pointers after
freeing them won’t solve all problems;

Question When would you use a pointer to a function?


Answer Pointers to functions are interesting when you pass them to other functions. A
function that takes function pointers says, in effect, “Part of what I do can be customized.
Give me a pointer to a function, and I’ll call it when that part of the job needs to be done.
That function can do its part for me.” This is known as a “callback.” It’s used a lot in
graphical user interface libraries, in which the style of a display is built into the library
but the contents of the display are part of the application. As a simpler example, say you
have an array of character pointers (char*s), and you want to sort it by the value of the
strings the character pointers point to. The standard qsort() function uses function
pointers to perform that task. qsort() takes four arguments,
a pointer to the beginning of the array,
the number of elements in the array,
the size of each array element, and
a comparison function, and returns an int.

Question Is it better to use malloc() or calloc()?


Answer Both the malloc() and the calloc() functions are used to allocate dynamic
memory. Each operates slightly different from the other. malloc() takes a size and returns
a pointer to a chunk of memory at least that big: void *malloc( size_t size );
calloc() takes a number of elements, and the size of each, and returns a pointer to a chunk
of memory at least big enough to hold them all: void *calloc( size_t numElements, size_t
sizeOfElement ); There’s one major difference and one minor difference between the two
functions. The major difference is that malloc() doesn’t initialize the allocated memory.
The first time malloc() gives you a particular chunk of memory, the memory might be
full of zeros. If memory has been allocated, freed, and reallocated, it probably has
whatever junk was left in it. That means, unfortunately, that a program might run
in simple cases (when memory is never reallocated) but break when used harder (and
when memory is reused). calloc() fills the allocated memory with all zero bits. That
means that anything there you’re going to use as a char or an int of any length, signed or
unsigned, is guaranteed to be zero. Anything you’re going to use as a pointer is set to all
zero bits. That’s usually a null pointer, but it’s not guaranteed.Anything you’re going to
use as a float or double is set to all zero bits; that’s a floating-point zero on some types of
machines, but not on all. The minor difference between the two is that calloc() returns an
array of objects; malloc() returns one object. Some people use calloc() to make clear that
they want an array.

Question What is the benefit of using an enum rather than a #define constant?
Answer The use of an enumeration constant (enum) has many advantages over using the
traditional symbolic constant style of #define. These advantages include a lower
maintenance requirement, improved program readability, and better debugging capability.
1) The first advantage is that enumerated constants are generated automatically by the
compiler. Conversely, symbolic constants must be manually assigned values by the
programmer. For instance, if you had an enumerated constant type for error codes that
could occur in your program, your enum definition could look something like this:
enum Error_Code
{
OUT_OF_MEMORY,
INSUFFICIENT_DISK_SPACE,
LOGIC_ERROR,
FILE_NOT_FOUND
};
In the preceding example, OUT_OF_MEMORY is automatically assigned the value of 0
(zero) by the compiler because it appears first in the definition. The compiler then
continues to automatically assign numbers to the enumerated constants, making
INSUFFICIENT_DISK_SPACE equal to 1, LOGIC_ERROR equal to 2, and
FILE_NOT_FOUND equal to 3, so on. If you were to approach the same example by
using symbolic constants, your code would look something like this:

#define OUT_OF_MEMORY 0
#define INSUFFICIENT_DISK_SPACE 1
#define LOGIC_ERROR 2
#define FILE_NOT_FOUND 3

values by the programmer. Each of the two methods arrives at the same result: four
constants assigned numeric values to represent error codes. Consider the maintenance
required, however, if you were to add two constants to represent the error codes
DRIVE_NOT_READY and CORRUPT_FILE. Using the enumeration constant
method, you simply would put these two constants anywhere in the enum definition. The
compiler would generate two unique values for these constants. Using the symbolic
constant method, you would have to manually assign two new numbers to these
constants. Additionally, you would want to ensure that the numbers you assign to these
constants are unique.
2) Another advantage of using the enumeration constant method is that your programs are
more readable and thus can be understood better by others who might have to update
your program later.
3) A third advantage to using enumeration constants is that some symbolic debuggers can
print the value of an enumeration constant. Conversely, most symbolic debuggers cannot
print the value of a symbolic constant. This can be an enormous help in debugging your
program, because if your program is stopped at a line that uses an enum, you can simply
inspect that constant and instantly know its value. On the other hand, because most
debuggers cannot print #define values, you would most likely have to search for
that value by manually looking it up in a header file.

Question How are portions of a program disabled in demo versions?


Answer If you are distributing a demo version of your program, the preprocessor can be
used to enable or disable portions of your program. The following portion of code shows
how this task is accomplished, using the preprocessor directives #if and #endif:
int save_document(char* doc_name)
{
#if DEMO_VERSION
printf(“Sorry! You can’t save documents using
the DEMO version of this program!n”);
return(0);
#endif
...
}

Question What is the difference between #include <file> and #include “file”?
Answer When writing your C program, you can include files in two ways. The first way
is to surround the file you want to include with the angled brackets < and >. This method
of inclusion tells the preprocessor to look for the file in the predefined default location.
This predefined default location is often an INCLUDE environment variable that denotes
the path to your include files. For instance, given the INCLUDE variable
INCLUDE=C:\COMPILER\INCLUDE;S:\SOURCE\HEADERS;
using the #include version of file inclusion, the compiler first checks the
C:\COMPILER\INCLUDE
directory for the specified file. If the file is not found there, the compiler then checks the
S:\SOURCE\HEADERS directory. If the file is still not found, the preprocessor checks
the current directory. The second way to include files is to surround the file you want to
include with double quotation marks. This method of inclusion tells the preprocessor to
look for the file in the current directory first, then look for it in the predefined locations
you have set up. Using the #include “file” version of file inclusion and applying it to the
preceding example, the preprocessor first checks the current directory for the specified
file. If the file is not found in the current directory, the C:COMPILERINCLUDE
directory is searched. If the file is still not found, the preprocessor checks the
S:SOURCEHEADERS directory. The #include method of file inclusion is often
used to include standard headers such as stdio.h or stdlib.h. This is because these
headers are rarely (if ever) modified, and they should always be read from your
compiler’s standard include file directory.
The #include “file” method of file inclusion is often used to include nonstandard header
files that you have created for use in your program. This is because these headers are
often modified in the current directory, and you will want the preprocessor to use your
newly modified version of the header rather than the older, unmodified version.

Question How many levels of pointers can you have?


Answer The answer depends on what you mean by “levels of pointers.” If you mean
“How many levels of indirection can you have in a single declaration?” the answer is “At
least 12.”
int i = 0;
int *ip01 = & i;
int **ip02 = & ip01;
int ***ip03 = & ip02;
int ****ip04 = & ip03;
int *****ip05 = & ip04;
int ******ip06 = & ip05;
int *******ip07 = & ip06;
int ********ip08 = & ip07;
int *********ip09 = & ip08;
int **********ip10 = & ip09;
int ***********ip11 = & ip10;
int ************ip12 = & ip11;
************ip12 = 1; /* i = 1 */
The ANSI C standard says all compilers must handle at least 12 levels. Your compiler
might support more.

Question How can I convert a string to a number?


Answer The standard C library provides several functions for converting strings to
numbers of all formats (integers, longs, floats, and so on) and vice versa.
The following functions can be used to convert strings to numbers:
Function Name Purpose atof() Converts a string to a double-precision
floating-point value. atoi() Converts a string to an integer. atol() Converts a string to a
long integer. strtod() Converts a string to a double-precision floating-point value and
reports any “leftover” numbers that could not be converted. strtol() Converts a string to a
long integer and reports any “leftover” numbers that could not be converted. strtoul()
Converts a string to an unsigned long integer and reports any “leftover” numbers that
could not be converted.

Question How do you print only part of a string?


Answer/* Use printf() to print the first 11 characters of source_str. */
printf(“First 11 characters: ‘%11.11s’n”, source_str);

Question What is the difference between a string copy (strcpy) and a memory copy
(memcpy)? When should each be us
Answer The strcpy() function is designed to work exclusively with strings. It copies each
byte of the source string to the destination string and stops when the terminating null
character () has been moved. On the other hand, the memcpy() function is designed to
work with any type of data. Because not all data ends with a null character, you must
provide the memcpy() function with the number of bytes you want to copy from the
source to the destination.

Question What is a pragma?


Answer The #pragma preprocessor directive allows each compiler to implement
compiler-specific features that can be turned on and off with the #pragma statement. For
instance, your compiler might support a feature called loop optimization. This feature can
be invoked as a command-line option or as a #pragma directive. To implement this option
using the #pragma directive, you would put the following line into your code:
#pragma loop_opt(on)
Conversely, you can turn off loop optimization by inserting the following line into your
code:
#pragma loop_opt(off)

Question How can I convert a number to a string?


Answer The standard C library provides several functions for converting numbers of all
formats (integers, longs, floats, and so on) to strings and vice versa The following
functions can be used to convert integers to strings: Function Name Purpose
itoa() Converts an integer value to a string. ltoa() Converts a long integer value to a
string. ultoa() Converts an unsigned long integer value to a string. The following
functions can be used to convert floating-point values to strings:
Function Name Purpose ecvt() Converts a double-precision floating-point value to a
string without an embedded decimal point. fcvt() Same as ecvt(), but forces the precision
to a specified number of digits. gcvt() Converts a double-precision floating-point value
to a string with an embedded decimal point.

Question Is it better to use a macro or a function?


Answer The answer depends on the situation you are writing code for. Macros have the
distinct advantage of being more efficient (and faster) than functions, because their
corresponding code is inserted directly into your source code at the point where the
macro is called. There is no overhead involved in using a macro like there is in placing a
call to a function. However, macros are generally small and cannot handle large, complex
coding constructs. A function is more suited for this type of situation. Additionally,
macros are expanded inline, which means that the code is replicated for each occurrence
of a macro. Your code therefore could be somewhat larger when you use macros than if
you were to use functions. Thus, the choice between using a macro and using a function
is one of deciding between the tradeoff of faster program speed versus smaller program
size. Generally, you should use macros to replace small, repeatable code sections, and
you should use functions for larger coding tasks that might require several lines of code.

Question How do you override a defined macro?


Answer You can use the #undef preprocessor directive to undefine (override) a previously
defined macro.

Question What are the standard predefined macros?


Answer The ANSI C standard defines six predefined macros for use in the C language:
Macro Name Purpose
_ _LINE_ _ Inserts the current source code line number in your code.
_ _FILE_ _ Inserts the current source code filename in your code.
_ _DATE_ _ Inserts the current date of compilation in your code.
_ _TIME_ _ Inserts the current time of compilation in your code.
_ _STDC_ _ Is set to 1 if you are enforcing strict ANSI C conformity.
_ _cplusplus Is defined if you are compiling a C++ program.

Question Can you define which header file to include at compile time?
Answer Yes. This can be done by using the #if, #else, and #endif preprocessor directives.
For example, certain compilers use different names for header files. One such case is
between Borland C++, which uses the header file alloc.h, and Microsoft C++,
which uses the header file malloc.h. Both of these headers serve the same purpose, and
each contains roughly the same definitions. If, however, you are writing a program that is
to support Borland C++ and Microsoft C++, you must define which header to include at
compile time. The following example shows how this can be done:
#ifdef _ _BORLANDC_ _
#include
#else
#include
#endif

Question How many levels deep can include files be nested?


Answer Even though there is no limit to the number of levels of nested include files you
can have, your compiler might run out of stack space while trying to include an
inordinately high number of files. This number varies according to your hardware
configuration and possibly your compiler.

Question Can a file other than a .h file be included with #include?


Answer The preprocessor will include whatever file you specify in your #include
statement. Therefore, if you have the line #include in your program, the file macros.inc
will be included in your precompiled program. It is, however, unusual programming
practice to put any file that does not have a .h or .hpp extension in an #include statement.
You should always put a .h extension on any of your C files you are going to include.
This method makes it easier for you and others to identify which files are being used for
preprocessing purposes. For instance, someone modifying or debugging your program
might not know to look at the macros.inc file for macro definitions. That person might try
in vain by searching all files with .h extensions and come up empty. If your file had been
named macros.h, the search would have included the macros.h file, and the searcher
would have been able to see what macros you defined in it.
Question What is Preprocessor?
AnswerThe preprocessor is used to modify your program according to the preprocessor
directives in your source code. Preprocessor directives (such as #define) give the
preprocessor specific instructions on how to modify your source code. The preprocessor
reads in all of your include files and the source code you are compiling and creates a
preprocessed version of your source code. This preprocessed version has all of its macros
and constant symbols replaced by their corresponding code and value assignments. If
your source code contains any conditional preprocessor directives (such as #if), the
preprocessor evaluates the condition and modifies your source code accordingly.
The preprocessor contains many features that are powerful to use, such as creating acros,
performing conditional compilation, inserting predefined environment variables into your
code, and turning compiler features on and off. For the professional programmer, in-
depth knowledge of the features of the preprocessor can be one of the keys to creating
fast, efficient programs.

Question How can you avoid including a header more than once?
Answer One easy technique to avoid multiple inclusions of the same header is to use the
#ifndef and #define preprocessor directives. When you create a header for your program,
you can #define a symbolic name that is unique to that header. You can use the
conditional preprocessor directive named #ifndef to check whether that symbolic name
has already been assigned. If it is assigned, you should not include the header, because it
has already been preprocessed. If it is not defined, you should define it to avoid any
further inclusions of the header. The following header illustrates this technique:

#ifndef _FILENAME_H
#define _FILENAME_H
#define VER_NUM “1.00.00”
#define REL_DATE “08/01/94”
#if _ _WINDOWS_ _
#define OS_VER “WINDOWS”
#else
#define OS_VER “DOS”
#endif
#endif

When the preprocessor encounters this header, it first checks to see whether
_FILENAME_H has been defined. If it hasn’t been defined, the header has not been
included yet, and the _FILENAME_H symbolic name is defined. Then, the rest of the
header is parsed until the last #endif is encountered, signaling the end of the conditional
#ifndef _FILENAME_H statement. Substitute the actual name of the header file
for “FILENAME” in the preceding example to make it applicable for your programs.

Question How can I make sure that my program is the only one accessing a file?
Answer By using the sopen() function you can open a file in shared mode and explicitly
deny reading and writing permissions to any other program but yours. This task is
accomplished by using the SH_DENYWR shared flag to denote that your program is
going to deny any writing or reading attempts by other programs. For example, the
following snippet of code shows a file being opened in shared mode, denying access to
all other files: /* Note that the sopen() function is not ANSI
compliant... */
fileHandle = sopen(“C:DATASETUP.DAT”, O_RDWR,
SH_DENYWR);
By issuing this statement, all other programs are denied access to the SETUP.DAT file. If
another program were to try to open SETUP.DAT for reading or writing, it would receive
an EACCES error code, denoting that access is denied to the file.

Question How can you restore a redirected standard stream?


Answer The preceding example showed how you can redirect a standard stream from
within your program. But what if later in your program you wanted to restore the
standard stream to its original state? By using the standard C library functions named
dup() and fdopen(), you can restore a standard stream such as stdout to its
original state. The dup() function duplicates a file handle. You can use the dup() function
to save the file handle corresponding to the stdout standard stream. The fdopen() function
opens a stream that has been duplicated with the dup() function.

Question What is the quickest searching method to use?


Answer A binary search, such as bsearch() performs, is much faster than a linear search.
A hashing algorithm can provide even faster searching. One particularly interesting and
fast method for searching is to keep the data in a “digital trie.” A digital trie offers the
prospect of being able to search for an item in essentially a constant amount of time,
independent of how many items are in the data set. A digital trie combines aspects of
binary searching, radix searching, and hashing. The term “digital trie” refers to the data
structure used to hold the items to be searched. It is a multilevel data structure that
branches N ways at each level.

Question What is the easiest searching method to use?


Answer Just as qsort() was the easiest sorting method, because it is part of the standard
library, bsearch() is the easiest searching method to use. If the given array is in the sorted
order bsearch() is the best method. Following is the prototype for bsearch():
void *bsearch(const void *key, const void *buf, size_t num, size_t size, int
(*comp)(const void *, const void*));
Another simple searching method is a linear search. A linear search is not as fast as
bsearch() for searching among a large number of items, but it is adequate for many
purposes. A linear search might be the only method available, if the data isn’t sorted or
can’t be accessed randomly. A linear search starts at the beginning and sequentially
compares the key to each element in the data set.

Question What is the easiest sorting method to use?


Answer 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));
Question What is the benefit of using const for declaring constants?
Answer The benefit of using the const keyword is that the compiler might be able to
make optimizations based on the knowledge that the value of the variable will not
change. In addition, the compiler will try to ensure that the values won’t be changed
inadvertently. Of course, the same benefits apply to #defined constants. The reason to use
const rather than #define to define a constant is that a const variable can be of any type
(such as a struct, which can’t be represented by a #defined constant). Also, because a
const variable is a real variable, it has an address that can be used, if needed, and it
resides in only one place in memory

Question Can static variables be declared in a header file?


Answer You can’t declare a static variable without defining it as well (this is because the
storage class modifiers static and extern are mutually exclusive). A static variable can be
defined in a header file, but this would cause each source file that included the header file
to have its own private copy of the variable, which is probably not what was intended.

Question When is a switch statement better than multiple if statements?


Answer A switch statement is generally best to use when you have more than two
conditional expressions based on a single variable of numeric type.

Question when should the volatile modifier be used?


Answer The volatile modifier is a directive to the compiler’s optimizer that operations
involving this variable should not be optimized in certain ways. There are two special
cases in which use of the volatile modifier is desirable. The first case involves memory-
mapped hardware (a device such as a graphics adaptor that appears to the computer’s
hardware as if it were part of the computer’s memory), and the second involves shared
memory (memory used by two or more programs running simultaneously).
Most computers have a set of registers that can be accessed faster than the computer’s
main memory. A good compiler will perform a kind of optimization called “redundant
load and store removal.” The compiler looks for places in the code where it can either
remove an instruction to load data from memory because the value is already in a
register, or remove an instruction to store data to memory because the value can stay in a
register until it is changed again anyway. If a variable is a pointer to something other
than normal memory, such as memory-mapped ports on a peripheral, redundant load and
store optimizations might be detrimental. For instance, here’s a piece of code that might
be used to time some operation:
time_t time_addition(volatile const struct timer
*t, int a)
{
int n;
int x;
time_t then;
x = 0;
then = t->value;
for (n = 0; n < 1000; n++)
{
x = x + a;
}
return t->value - then;
}

this code, the variable t->value is actually a hardware counter that is being incremented
as time passes. The function adds the value of a to x 1000 times, and it returns the amount
the timer was incremented by while the 1000 additions were being performed. Without
the volatile modifier, a clever optimizer might assume that the value of t does not change
during the execution of the function, because there is no statement that explicitly changes
it. In that case, there’s no need to read it from memory a second time and subtract it,
because the answer will always be 0. The compiler might therefore “optimize” the
function by making it always return 0. If a variable points to data in shared memory,
you also don’t want the compiler to perform redundant load and store optimizations.
Shared memory is normally used to enable two programs to communicate with each other
by having one program store data in the shared portion of memory and the other program
read the same portion of memory. If the compiler optimizes away a load or store of
shared memory, communication between the two programs will be affected.
Question What is a const pointer?
AnswerThe access modifier keyword const is a promise the programmer makes to the
compiler that the value of a variable will not be changed after it is initialized. The
compiler will enforce that promise as best it can by not enabling the programmer to write
code which modifies a variable that has been declared const. A “const pointer,” or more
correctly, a “pointer to const,” is a pointer which points to data that is const
(constant, or unchanging). A pointer to const is declared by putting the word const at the
beginning of the pointer declaration. This declares a pointer which points to data that
can’t be modified. The pointer itself can be modified. The following example illustrates
some legal and illegal uses of a const pointer:
const char *str = “hello”;
char c = *str /* legal */
str++; /* legal */
*str = ‘a’; /* illegal */
str[1] = ‘b’; /* illegal */

Question What is the quickest sorting method to use?


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

C++ Interview Questions


Question What is a class?
Answer 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.

Question What is an object?


Answer Object is a software bundle of variables and related methods. Objects have state
and behavior.

Question What is a template?


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

Question What is abstraction?


Answer Abstraction is of the process of hiding unwanted details from the user.

Question What is virtual constructors/ destructors?


Answer 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 all
derived-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 and
multiple 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<}

Question what is the difference between an object and a class?


Answer 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 the
execution 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 eventually
destroyed. Also during that lifetime, the attributes of the object may undergo significant
change.

Question What is the difference between class and structure?


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

Question What is virtual class and friend


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

Question What is polymorphism? Explain with an example?


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

Question What is public, protected, private?


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

Question What is RTTI?


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

Question What is friend function?


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

Question What is function overloading and operator overloading?


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

Question What is namespace?


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

Question What do you mean by inline function?


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

Question What do you mean by pure virtual functions?


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;
};

Question What is a scope resolution operator?


Answer A scope resolution operator (::), can be used to define the member functions of a
class outside the class.
Question Difference between realloc() and free()?
Answer 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 deallocated with the free or realloc subroutines.
Undefined results occur if the Pointer parameter is not a valid pointer.

Question What are virtual functions?


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

Question Explain kill() and its possible return values.


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

Question How many prompts are available in a UNIX system?


Answer Two prompts, PS1 (Primary Prompt), PS2 (Secondary Prompt).

Question How to terminate a process which is running and the specialty on


command kill
0?
Answer With the help of kill command we can terminate the process. Syntax: kill pid
Kill 0 - kills all processes in your system except the login shell.

Question Is it possible to create new a file system in UNIX?


Answer Yes, ‘mkfs’ is used to create a new file system.
Question What are shell variables?
Answer Shell variables are special variables, a name-value pair created and maintained
by the shell. Example: PATH, HOME, MAIL and TERM

Question What daemon is responsible for tracking events on your system?


Answer : syslogd The syslogd daemon is responsible for tracking system information and
saving it to specified log files.

Question What is the name and path of the default configuration file used by the
syslogd
Daemon?
Answer : /etc/syslog.conf If no configuration file is specified when starting syslogd, then
it will start up with the configuration specified in the /etc/syslog.conf file.

Question which command is used to delete all files in the current directory and all
its sub-directories?
Answer rm -r *

Question Write a command to display a file’s contents in various formats?


Answer $od -cbd file_name c - character, b - binary (octal), d-decimal,
od=Octal Dump.

Question Write a command to kill the last background job?


Answer Kill $!

MEMORY MANAGEMENT
Const Data: The const data area stores string literals and other data whose values are
known at compile time. No objects of class type can exist in this area. All data in this
area is available during the entire lifetime of the program. Further, all of this data is read-
only, and the results of trying to modify it are undefined.

Stack: The stack stores automatic variables. Typically allocation is much faster than for
dynamic storage (heap or free store) because a memory allocation involves only pointer
increment rather than more complex management. Objects are constructed immediately
after memory is allocated and destroyed immediately before memory is deallocated, so
there is no opportunity for programmers to directly manipulate allocated but uninitialized
stack space.

Free Store: The free store is one of the two dynamic memory areas, allocated/freed by
new/delete. Object lifetime can be less than the time the storage is allocated; that is, free
store objects can have memory allocated without being immediately initialized, and can
be destroyed without the memory being immediately deallocated. During the period
when the storage is allocated but outside the object's lifetime, the storage may be
accessed and manipulated through a void* but none of the proto-object's nonstatic
members or member functions may be accessed, have their addresses taken, or be
otherwise manipulated.

Heap: The heap is the other dynamic memory area, allocated/freed by malloc / free and
their variants. Note that while the default global new and delete might be implemented in
terms of malloc and free by a particular compiler, the heap is not the same as free store
and memory allocated in one area cannot be safely deallocated in the other. Memory
allocated from the heap can be used for objects of class type by placement-new
construction and explicit destruction. If so used, the notes about free store object lifetime
apply similarly here.

Global/Static: Global or static variables and objects have their storage allocated at
program startup, but may not be initialized until after the program has begun executing.
For instance, a static variable in a function is initialized only the first time program
execution passes through its definition. The order of initialization of global variables
across translation units is not defined, and special care is needed to manage
dependencies between global objects (including class static’s). As always, uninitialized
Proto- objects' storage may be accessed and manipulated through a void* but no
nonstatic members or member functions may be used or referenced outside the object's
actual lifetime.

Automatic Storage
Local objects that are not explicitly declared static or extern, local objects that are
declared auto or register, and function arguments have automatic storage. This type of
storage is also called stack memory.

Static Storage

Global objects, static data members of a class, namespace variables, and static variables
in functions reside in static memory.

NOTE:

Static- storage allocated at link time, initialized at load time, and released on termination.
Stack- storage that is allocated, initialized, and released on a last in first out basis.
Heap- storage that can be dynamically allocated, initialized, and released.

WHERE IS A POINTER STORED?


A pointer can be stored in any of the same locations that any other variable can be stored
but is generally not stored on the heap. It can be defined and stored globally, or it can be
defined local to a function and stored on the stack. The size of the pointer depends on the
implementation and for 32 bit operating systems, it generally requires four bytes of
storage space. This is not a requirement however, a compiler writer can use any number
of bytes desired to store a pointer.

Keep in mind, a pointer is like any other variable in the sense that it requires storage
space somewhere in the computer's memory, but it is not like most variables because it
contains no data, only an address. Since it is an address, it actually contains a number
referring to some memory location.

Class Object Storage:

Static: In C++, the size of any object that is declared static can be determined at compile
time, and so storage for the object can be allocated by the linker. The object will be
created just before the program begins to execute, and will be destroyed just before the
program terminates. It is important to note that you have little or no control over the order
in which static objects are created or destroyed. (This can be a major source of portability
problems.)
Stack: In C++, an object that is declared directly is created on the stack. Objects are
destroyed in reverse order of creation. This is done automatically on exit of the block
they were created in.

Heap: Objects created with the new operator are placed on the heap. They will persist
until explicitly destroyed, or the program terminates. You cannot refer to such an object
directly, you need to use a pointer. Every object created with new should have a
corresponding delete, otherwise you will get memory leaks.

Calling Functions:
The parameters to procedure and function calls, and the return result are placed on the
stack. What is actually placed on the stack depends on the type of parameter. This is very
important to understand when it comes to passing objects to a procedure and returning
objects from a procedure. The default passing convention for parameters is by value. That
is, instead of the actual parameter, a copy of it is placed on the stack. The same holds for
the return value. A place is reserved for the return value on the stack, and when the return
is executed the value to be returned is copied into this place.

Passing a parameter by reference avoids the copying of values by putting a pointer to the
parameter on the stack. Returning by reference is similar

NOTE:
When the parameter appearing in the argument list is not of the correct type, such as
providing an int argument when a double is required, or having an expression in the
argument position. In that case a temporary object is created on the stack to store the
actual parameter. If that temporary object is being passed by const reference (it must be
const) then a pointer to the temporary is passed as the parameter.

Dynamic Memory Allocation


Memory allocation provides a way to dynamically create buffers and arrays. Dynamic
means that the space is allocated in memory as the program is executing. On many
occasions the sizes of objects will not be known until run time.

How to Allocate Memory With Malloc()


The standard library function malloc is commonly used to allocate memory. Its prototype
is:

void *malloc (size_t nbytes);

Malloc returns a void pointer to the allocated buffer. This pointer must be cast into the
proper type to access the data to be stored in the buffer. On failure, malloc returns a null
pointer.

How to Free Memory With Free ()


When using dynamically allocated memory, it is necessary for the programmer to free the
memory after its use.
void free (void *pt);

It is not necessary to cast the pointer argument back to void. The compiler handles this
conversion.

Disadvantage of New:
One disadvantage of New is that there is no way to reallocate memory. With Malloc you
can use Realloc to extend the amount of memory quickly. With New you have to create a
new chunk of memory with the modified size and then copy over the data from the
original buffer and then delete the original buffer. This can be a slow process.

Mixing Memory Allocation:

Never use malloc () to allocate memory and then delete it. Likewise never use new to
allocate memory and then free() it. These are not compile time errors, but can cause
spectacular program crashes which again, are difficult to debug. Use the memory
allocation routines consistently.
Don't mix new /delete with C allocation/ deallocation functions, or the behavior is
undefined. Remember that new may throw exceptions (from failed memory allocation or
from constructor).

Can I free () pointers allocated with new? Can I delete pointers allocated with malloc ()?
NO
If you allocated via pointer = new char [nbytes], you must use delete [] p; you must not
use free (p). Or if you allocated via pointer = malloc (nbytes), you must use free (p); you
must not use delete [] p or delete p! Mixing these up could cause a catastrophic failure at
runtime if the code was ported to a new machine, a new compiler, or even a new version
of the same compiler.

Shallow Copies :
The default copy constructor and assignment operator make shallow copies.

Don't write a copy constructor if shallow copies are ok:


If the object has no pointers to dynamically allocated memory, a shallow copy is probably
sufficient. Therefore the default copy constructor, default assignment operator, and
default destructor are ok and you don't need to write your own.

Deep copies :
If an object has pointers to dynamically allocated memory, and the dynamically allocated
memory needs to be copied when the original object is copied, then a deep copy is
required.
A class that requires deep copies generally needs:
A constructor to either make an initial allocation or set the pointer to NULL.
A destructor to delete the dynamically allocated memory.
A copy constructor to make a copy of the dynamically allocated memory.
An overloaded assignment operator to make a copy of the dynamically allocated memory.

DATABASE Interview Questions

Question TRUNCATE TABLE EMP; DELETE FROM EMP;


Will the outputs of the above two commands differ?
Answer Both will result in deleting all the rows in the table EMP.
Question What are the privileges that can be granted on a table by a user to others?
Answer Insert, update, delete, select, references, index, execute, alter, all.
Question What command is used to get back the privileges offered by the GRANT
command?
Answer REVOKE.
Question What is the difference between TRUNCATE and DELETE commands?
Answer TRUNCATE is a DDL command whereas DELETE is a DML command. Hence
DELETE operation can be rolled back, but TRUNCATE operation cannot be rolled back.
WHERE clause can be used with DELETE and not with TRUNCATE.
Question What is the parameter substitution symbol used with INSERT INTO
command?
Answer&
Question What is the use of CASCADE CONSTRAINTS?
Answer When this clause is used with the DROP command, a parent table can be dropped
even when a child table exists.
Question What is the use of the DROP option in the ALTER TABLE command?
Answer It is used to drop constraints specified on the table.
Question Which command displays the SQL command in the SQL buffer, and then
executes it?
Answer RUN.
Question Which command executes the contents of a specified file?
Answer START or @.
Question Which date function is used to find the difference between two dates?
Answer MONTHS_BETWEEN.
Question Which function is used to find the largest integer less than or equal to a
specificvalue?
Answer FLOOR.
Question Which system table contains information on constraints on all the tables
created?
Answer USER_CONSTRAINTS.
Question Why does the following command give a compilation error?
DROP TABLE &TABLE_NAME;
Answer Variable names should start with an alphabet. Here the table name starts with an
'&' symbol.
To see current user name
Sql> show user;
Change SQL prompt name
SQL> set sqlprompt “sukhvir > “
sukhvir >
How do I display row number with records?
To achieve this use rownum pseudocolumn with query, like SQL> SQL> select rownum,
ename from emp;
Output:
1 sukhvir
2 nauhwar
Find out nthhighest salary from emp table
SELECT DISTINCT (a.sal) FROM EMP A WHERE&N = (SELECT COUNT
(DISTINCT (b.sal)) FROM EMP B WHEREa.sal<=b.sal);
Display Odd/ Evennumber of records
Odd number of records:
select * from emp where(rowid,1) in (select rowid, mod(rownum,2) from emp);
135
Even numberof records:
select * from emp where (rowid,0) in (select rowid,mod(rownum,2) from emp)
246
Any three PL/SQLExceptions?
Too_many_rows, No_Data_Found, Value_Error, Zero_Error,Others
What are PL/SQLCursor Exceptions?
Cursor_Already_Open, Invalid_Cursor
What is themaximum number of triggers, can apply to a single table?
12 triggers.
Question Can a function take OUT parameters. If notwhy?
Answer No. A function has to return a value, an OUT parameter cannotreturn a value.
Question Which is more faster - IN orEXISTS?
Answer EXISTS is more faster than IN because EXISTS returns a Booleanvalue whereas
IN returns a value.
Question Which datatype is used for storing graphics andimages?
Answer LONG RAW data type is used for storing BLOB's (binary largeobjects).
Question Wherethe integrity constraints are stored in Data Dictionary?
Answer The integrity constraints are stored inUSER_CONSTRAINTS.
Question When does a Transaction end?
Answer When it is committed or Rollbacked.
Question When do you use WHERE clause and when do you useHAVING clause?
Answer HAVING clause is used when you want to specify acondition for a group
function and it is written after GROUP BY clause. TheWHERE clause is used when you
want to specify a condition for columns, singlerow functions except group functions and
it is written before GROUP BY clause ifit is used.
Question When can Hash Cluster used?
Answer Hash clusters are better choice when a table is often queried withequality queries.
For such queries the specified cluster key value is hashed.The resulting hash key value
points directly to the area on disk that stores thespecified rows.
Question What will happen after commitstatement
Answer Cursor C1 is Select empno, ename from emp; Begin open C1;loop
Fetch C1 into eno.ename; Exit When C1 %notfound;----- commit;
end loop; end; The cursor having query as SELECT .... FOR UPDATE getsclosed after
COMMIT/ROLLBACK. The cursor havingquery as SELECT.... does not
get closed even after COMMIT/ROLLBACK.
Question What WHERE CURRENT OF clause does in acursor?
Answer LOOP SELECT num_credits INTO v_numcredits FROM
Classes WHERE dept=123 and course=101; UPDATE students SETcurrent_credits=
current_credits+v_numcredits WHERE CURRENT OF X; END LOOPCOMMIT; END;
Question What should be the return type for a cursorvariable. Can we use a scalar
data type as returntype?
Answer The return type for a cursor must be a record type. It can bedeclared explicitly as
a user-defined or %ROWTYPE can be used. eg TYPEt_studentsref IS REF CURSOR
RETURN students%ROWTYPE
Question What is use of a cursor variable? How it isdefined?
Answer A cursor variable is associated with different statements at runtime, which can
hold different values at run time. Static cursors can only beassociated with one run time
query. A cursor variable is reference type (like apointer in C). Declaring a cursor variable:
TYPE type_name IS REF CURSOR RETURNreturn_type type_name is the name of the
reference type,return_type is a recordtype indicating the types of the select list that will
eventually be returned bythe cursor variable.
Question What is trigger associated with the timer?
Answer When-timer-expired.
Question What is the use of Redo LogInformation
Answer The Information in a redo log file is used only to recover thedatabase from a
system or media failure prevents database data from beingwritten to a database's data
files.
Question What is the use of Control File?
Answer When an instance of an ORACLE database is started, its controlfile is used to
identify the database and redo log files that must be opened fordatabase operation to
proceed. It is also used in database recovery.
Question What is the Subquery?
Answer Sub query is a query whose return values are used in filteringconditions of the
main query.
Question What is the purpose of acluster?
Answer Oracle does not allow a user to specifically locate tables, sincethat is a part
of the function of the RDBMS. However, for the purpose of increasingperformance,
oracle allows a developer to create a CLUSTER. A CLUSTER provides ameans for
storing data from different tables together for faster retrieval thanif the table placement
were left to the RDBMS.
Question What is the maximum number of CHECK constraintsthat can be defined
on a column?
Answer No Limit.
Question What isthe function of Redo Log?
Answer The Primary function of the redo log is to recordall changes made to
data.Question Whatis the fastest way of accessing a row in a table?
Answer Using ROWID.CONSTRAINTS
Question What is the basic structure ofPL/SQL
Answer PL/SQL uses block structure as its basic structure. Anonymousblocks or nested
blocks can be used in PL/SQL.
Question What is Table ?
Answer A table is the basic unit of data storage in an ORACLE database.The tables of a
database hold all of the user accessible data. Table data isstored in rows and columns.
Question What is SYSTEM tablespace and when is itCreated?
Answer Every ORACLE database contains a tablespace named SYSTEM, which
isautomatically created when the database is created. The SYSTEM tablespace
alwayscontains the data dictionary tables for the entire database.
Question What is self-referential integrity constraint?
Answer If a foreign key reference a parent key of the same table is called self-referential
integrity constraint.
Question What isschema?
Answer A schema is collection of database objects of a User.
Question What is ROWID ?
Answer ROWID is a pseudo column attached to each row of a table. It is 18character
long, blockno, rownumber are the components of ROWID.
Question What is Row Chaining?
Answer In Circumstances, all of the data for a row in a table may not beable to fit in the
same data block. When this occurs , the data for the row is stored in achain of data block
(one or more) reserved for that segment.
Question What is Rollback Segment?
Answer A Database contains one or more Rollback Segments to temporarilystore "undo"
information.
Question What is Restricted Mode of Instance Startup?
Answer An instance can be started in (or later altered to be in)restricted mode so that
when the database is open connections are limited onlyto those whose user accounts have
been granted the RESTRICTED SESSION systemprivilege.
Question What is Referential Integrity?
Answer Maintaining data integrity through a set of rules that restrictthe values of one or
more columns of the tables based on the values of primarykey or unique key of the
referenced table.
Question What is Read-Only Transaction?
Answer A Read-Only transaction ensures that the results of each queryexecuted in the
transaction are consistant with respect to the same point intime.
Question What is Raise_application_error?
Answer Raise_application_error is a procedure of package DBMS_STANDARDwhich
allows to issue an user_defined error messages from stored sub-program ordatabase
trigger.
Question What is Public Database Link?
Answer Public database link is created for the special user group PUBLIC.A public
database link can be used when any user in the associated databasespecifies a global
object name in a SQL statement or objectdefinition.
Question What is Private Database Link?
Answer Private database link is created on behalf of a specific user. Aprivate database
link can be used only when the owner of the link specifies aglobal object name in a SQL
statement or in the definition of the owner's views orprocedures.
Question What is Pragma EXECPTION_INIT ? Explain theusage ?
Answer The PRAGMA EXECPTION_INIT tells the complier to associate anexception
with an oracle error. To get an error message of a specific oracleerror. e.g. PRAGMA
EXCEPTION_INIT (exception name, oracle errornumber)
Question What is PL/SQL table?
Answer Objects of type TABLE are called "PL/SQL tables", which aremodeled as (but
not the same as) database tables, PL/SQL tables use a primaryPL/SQL tables can have
one column and a primary key. Cursors
Question What is PL/SQL?
Answer PL/SQL is a procedural language that has both interactive SQL andprocedural
programming language constructs such as iteration, conditionalbranching.
Question What is Partial Backup?
Answer A Partial Backup is any operating system backup short of a fullbackup, taken
while the database is open or shut down.
Question What is Parallel Server?
Answer Multiple instances accessing the same database (Only In Multi-
CPUenvironments)
Question What is Overloading ofprocedures
Answer The Same procedure name is repeated with parameters of differentdatatypes and
parameters in different positions, varying number of parameters iscalled overloading of
procedures. e.g. DBMS_OUTPUT put_line
Question What is On-line RedoLog?
Answer The On-line Redo Log is a set of tow or more on-line redo filesthat record all
committed changes made to the database. Whenever a transaction iscommitted, the
corresponding redo entries temporarily stores in redo log buffersof the SGA are written to
an on-line redo log file by the background processLGWR. The on-line redo log files are
used in cyclical fashion.
Question What is ON DELETE CASCADE?
Answer When ON DELETE CASCADE is specified ORACLE maintains
referentialintegrity by automatically removing dependent foreign key values if a
referencedprimary or unique key value is removed.
Question Can a primary key contain more than one columns?
Answer Yes
Question Can a Tablespace hold objects from differentSchemes ?
Answer Yes.
Question Can a View based on another View?
Answer Yes.
Question Can a view be updated/inserted/deleted? If Yesunder what conditions ?
Answer A View can be updated/deleted/inserted if it has only one basetable if the view is
based on columns from one or more tables then insert,update and delete is not possible.
Question Can an Integrity Constraint be enforced on atable if some existing table
data does not satisfy the constraint?
Answer No.
Question Can Full Backup be performed when the databaseis open ?
Answer No.
Question Can objects of the same Schema reside indifferent tablespaces.?
Answer Yes.
Question What is an Index Segment?
Answer Each Index has an Index segment that stores all of its data.
Question Can the default values be assigned to actualparameters?
Answer Yes
Question Can you use a commit statement within a databasetrigger?
Answer No
Question Describe Referential Integrity?
Answer A rule defined on a column (or set of columns) in one table thatallows the insert
or update of a row only if the value for the column or set ofcolumns (the dependent
value) matches a value in a column of a related table(the referenced value). It also
specifies the type of data manipulation allowedon referenced data and the action to be
performed on dependent data as a result of any action on referenced data.
Question Difference between an implicit&an explicitcursor
Answer PL/SQL declares a cursor implicitly for all SQL data manipulationstatements,
including quries that return only one row. However, queries thatreturn more than one row
you must declare an explicit cursor or use a cursor FORloop. Explicit cursor is a cursor in
which the cursor name is explicitlyassigned to a SELECT statement via the
CURSOR...IS statement. An implicit cursoris used for all SQL statements Declare, Open,
Fetch, Close. An explicit cursorsare used to process multirow SELECT statements An
implicit cursor is used toprocess INSERT, UPDATE, DELETE and single row
SELECT. .INTO statements.
Question Difference between database triggers and formtriggers?
Answer- Data base trigger(DBT) fires when a DML operation is performed ona data base
table. Form trigger(FT) Fires when user presses a key or navigatesbetween fields on the
screen -Can be row level or statement level No distinctionbetween row level and
statement level. -Canmanipulate data stored in Oracle tables via SQLCan manipulate
data in Oracle tables as well as variables in forms. -Can befired from any session
executing the triggering DML statements. Can be firedonly from the form that define the
trigger. -Can cause other database triggersto fire.Can cause other database triggers to fire,
but not other form triggers.
Question Difference between NO DATA FOUND and%NOTFOUND
Answer NO DATA FOUND is an exception raised only for the
SELECT....INTOstatements when the where clause of the querydoes not match any rows.
When thewhere clause of the explicit cursor does not match any rows the
%NOTFOUNDattribute is set to TRUE instead.
Question Difference between procedure andfunction
Answer Functions are named PL/SQL blocks that return a value and can becalled with
arguments procedure a named block that can be called with parameter.A procedure all is a
PL/SQL statement by itself, while a Function call is calledas part of an expression.
Question Difference between SUBSTR and INSTR?
Answer INSTR (String1,String2(n,(m)),INSTR returns the position of themth occurrence
of the string 2 instring1. The search begins from nth position ofstring1.SUBSTR (String1
n,m)SUBSTR returns a character string of size m in string1,starting fromnth position of
string1.
Question Display the number value inWords?
Answer SQL>select sal, (to_char(to_date(sal,'j'), 'jsp')) from emp;the output like,
SAL (TO_CHAR(TO_DATE(SAL,'J'),'JSP'))
----------------------------------------------
800 eight hundred
1600 one thousand six hundred
1250 one thousand two hundred fifty
If you want to add some text like, Rs. Three Thousand only. SQL>select sal "Salary ",
(' Rs. '|| (to_char(to_date(sal,'j'), 'Jsp'))|| ' only.')) "Sal in Words"from emp /
Salary Sal in Words--------------------------------------------------
800 Rs. Eight Hundred only.
1600 Rs. One Thousand Six Hundred only.
1250 Rs. One Thousand Two Hundred Fifty only.
Question Do View contain Data ?
Answer Views do not contain or store data.
Question Explain how procedures and functions are calledin a PL/SQL block ?
Answer Function is called as part of an expression. sal := calculate_sal('a822');
procedure is called as a PL/SQL statement calculate_bonus('A822');
Question Explain the relationship among Database,Tablespace and Data file.
Answer Each databases logically divided into one or more tablespaces oneor more data
files are explicitly created for each tablespace.
Question Explain UNION,MINUS,UNION ALL, INTERSECT
Answer INTERSECT returns all distinct rows selected by both queries.MINUS - returns
all distinct rows selected by the first query but not by thesecond. UNION - returns all
distinct rows selected by either query UNION ALL –returns all rows selected by either
query, including all duplicates.
Question Find out nth highest salary from emptable
Answer SELECT DISTINCT (a.sal) FROM EMP A WHERE&N = (SELECT
COUNT(DISTINCT (b.sal)) FROM EMP B WHERE a.sal<=b.sal); For Eg:-
Enter value for n: 2 SAL
---------
3700
Question Give the structure of the function?
Answer FUNCTION name (argument list .....) Return datatype is localvariable
declarations Begin executable statements Exception execution handlersEnd;

Question Give the structure of theprocedure


Answer PROCEDURE name (parameter list.....) is local variabledeclarations BEGIN
Executable statements. Exception. exception handlersend;
Question How are Indexes Update?
Answer Indexes are automatically maintained and used by ORACLE. Changesto table
data are automatically incorporated into all relevantindexes.
Question How do you find the numbert of rows in a Table?
Answer A bad answer is count them (SELECT COUNT(*) FROM table_name) Agood
answer is :- 'By generating SQL to ANALYZE TABLE table_name COUNTSTATISTICS
by querying Oracle System Catalogues (e.g. USER_TABLES orALL_TABLES). The
best answer is to refer to the utility which Oracle releasedwhich makes it unnecessary to
do ANALYZE TABLE for each Tableindividually.
How many LONG columns are allowed in a table ? Is itpossible to use LONG
columns in WHERE clause or ORDER BY?
Answer Only one LONG columns is allowed. It is not possible to use LONGcolumn in
WHERE or ORDER BY clause.
Question How many types of database triggers can bespecified on a table ? What
are they ?
Answer Insert Update Delete Before Row o.k. o.k. o.k. After Row o.k. o.k.o.k.
Before Statement o.k. o.k. o.k. After Statement o.k. o.k. o.k. If FOREACH ROW clause
is specified, then the trigger for each Row affected by thestatement. If WHEN clause is
specified, the trigger fires according to thereturned Boolean value.
Question How to access the current value and next valuefrom a sequence ? Is it
possible to access the current value in a session beforeaccessing next value ?
Answer Sequence name CURRVAL, Sequence nameNEXTVAL. It is not possible.Only if
you access next value in the session, current value can beaccessed.
Question How to define Data Block size?
Answer A data block size is specified for each ORACLE database when thedatabase is
created. A database users and allocated free database space inORACLE datablocks. Block
size is specified in INIT.ORA file and can’t be changedlatter.
Question How will you a activate/deactivate integrity constraints?
Answer The integrity constraints can be enabled or disabled by ALTERTABLE ENABLE
constraint/DISABLE constraint.
How will you delete duplicating rows from a base table?
Answer delete from table_name where rowid not in (select max(rowid) fromtable group
by duplicate_values_field_name); or deleteduplicate_values_field_name dv from
table_name ta where rowid<(select min(rowid) from table_name tb whereta.dv=tb.dv);
Question How you open and close a cursor variable. Why itis required?
Answer OPEN cursor variable FOR SELECT...Statement CLOSE cursor variableIn order
to associate a cursor variable with a particular SELECT statement OPENsyntax is used.
In order to free the resources used for the query CLOSEstatement is used.
Question How you were passing cursor variables in PL/SQL2.2?
Answer In PL/SQL 2.2 cursor variables cannot be declared in a package.This is because
the storage for a cursor variable has to be allocated usingPro*C or OCI with version 2.2,
the only means of passing a cursor variable to a PL/SQL block is via bindvariable or a
procedure parameter.
Question How you will avoid duplicating records in aquery?
Answer By using DISTINCT
Question How you will avoid your query from usingindexes?
Answer SELECT * FROM emp Where emp_no+' '=12345; i.e you have toconcatenate
the column name with space within codes in the where condition.SELECT /*+ FULL(a)
*/ ename, emp_no from emp where emp_no=1234; i.e usingHINTS
Question If a View on a single base table is manipulatedwill the changes be reflected
on the base table?
Answer If changes are made to the tables which are base tables of a viewwill the changes
be reference on the view.
Question If an unique key constraint on DATE column iscreated, will it validate the
rows that are inserted with SYSDATE?
Answer It won't, Because SYSDATE format contains time attached withit.
Question Is it possible to use Transaction controlStatements such a ROLLBACK or
COMMIT in Database Trigger ? Why?
Answer It is not possible. As triggers are defined for each table, if youuse COMMIT of
ROLLBACK in a trigger, it affects logical transaction processing.
Question min value. sql Select the Nth lowest value froma table
Answer select level, min('col_name') from my_table where level = '&n'connect by prior
('col_name')<'col_name') group by level; Example: Given a tablecalled emp with the
following columns: -- id number -- name varchar2(20) -- salnumber --
-- For the second lowest salary: -- select level, min(sal) fromemp
-- where level=2 -- connect by prior sal<sal -- group by level
Question Name the tables where characteristics of Package, procedure andfunctions are
stored
Answer User_objects, User_Source and User_error.
Question Suppose a customer table is having differentcolumns like customer no,
payments. What will be the query to select top three maxpayments?
Answer SELECT customer_no, payments from customer C1 WHERE
3<=(SELECTCOUNT(*) from customer C2 WHERE C1.payment<= C2.payment)
Question There is a % sign in one field of a column. Whatwill be the query to find
it?
Answer'' Should be used before '%'.
Question What a SELECT FOR UPDATE cursorrepresent.
Answer SELECT......FROM......FOR......UPDATE[OF column-reference][NOWAIT]The
processing done in a fetch loop modifies the rows that have been retrievedby the
cursor. A convenient way of modifying the rows is done by a method withtwo parts: the
FOR UPDATE clause in the cursor declaration, WHERE CURRENT OFCLAUSE
in an UPDATE or declaration statement.
Question What are advantages fo StoredProcedures
Answer Extensibility, Modularity, Reusability, Maintainability and onetime compilation.
Question What are Clusters?
Answer Clusters are groups of one or more tables physically storestogether to share
common columns and are often used together.
Question What are cursor attributes?
Answer- %ROWCOUNT -%NOTFOUND -%FOUND-%ISOPEN
Question What are different modes of parameters used infunctions and procedures?
Answer- IN -OUT -INOUT
Question What are different Oracle databaseobjects?
Answer- TABLES –VIEWS –INDEXES –SYNONYMS –SEQUENCES
-TABLESPACESetc
Question What are ORACLE PRECOMPILERS?
Answer Using ORACLE PRECOMPILERS, SQL statements and PL/SQL blocks can
becontained inside 3GL programs written in C,C++,COBOL,PASCAL, FORTRAN,PL/1
ANDADA. The Precompilers are known as Pro*C,Pro*Cobol,... This form of PL/SQL
isknown as embedded pl/sql,the language in which pl/sql is embedded is known asthe
host language. The prcompiler translates the embedded SQL and pl/sqlststements into
calls to the precompiler runtime library.The output must becompiled and linked with this
library to creater an executable.
Question What are Schema Objects?
Answer Schema objects are the logical structures that directly refer tothe database's data.
Schema objects include tables, views, sequences, synonyms, indexes,clusters, database
triggers, procedures, functions packages and databaselinks.
Question What are the advantages of operating a databasein ARCHIVELOG mode
over operating it in NO ARCHIVELOG mode?
Answer Complete database recovery from disk failure is possible only inARCHIVELOG
mode. Online database backup is possible only in ARCHIVELOGmode.
Question What are the advantages of Views?
Answer Provide an additional level of table security, by restrictingaccess to a
predetermined set of rows and columns of a table. Hide data complexity.Simplify
commands for the user. Present the data in a different perspective fromthat of the base
table. Store complex queries.
Question What are the Characteristics of Data Files?
Answer A data file can be associated with only one database. Once createda data file can't
change size. One or more data files form a logical unit ofdatabase storage called a
tablespace.
Question What are the components of a PL/SQL Block?
Answer Declarative part, Executable part and Exception part. DatatypesPL/SQL
Question What arethe components of Logical database structure of ORACLE
database?
Answer Tablespaces and the Database's Schema Objects.
Question What are the components of Physical databasestructure of Oracle
Database?
Answer ORACLE database is comprised of three types of files. One or moreData files,
two are more Redo Log files, and one or more Controlfiles.
Question What are the data types allowed in a table?
Answer CHAR,VARCHAR2,NUMBER,DATE,RAW,LONG and LONG RAW.
Question What are the different modes of mounting aDatabase with the Parallel
Server ?
Answer Exclusive Mode If the first instance that mounts a database doesso in exclusive
mode, only that Instance can mount the database. Parallel ModeIf the first instance that
mounts a database is started in parallel mode, otherinstances that are started in parallel
mode can also mount thedatabase.
Question What are the different type ofSegments
Answer Data Segment, Index Segment, Rollback Segment and TemporarySegment.
Question What are the Limitations of a CHECK Constraint?
Answer The condition must be a Boolean expression evaluated using thevalues in the row
being inserted or updated and can't contain sub queries,sequence, the
SYSDATE,UID,USER or USERENV SQL functions, or the pseudocolumns
LEVEL or ROWNUM.
Question What are the Referential actions supported byFOREIGN KEY integrity
constraint
Answer UPDATE and DELETE Restrict - A referential integrity rule thatdisallows the
update or deletion of referenced data. DELETE Cascade - When areferenced row is
deleted all associated dependent rows are deleted.
Question What are the return values of functions SQLCODEand SQLERRM ?
Answer SQLCODE returns the latest code of the error that has occurred.SQLERRM
returns the relevant error message of the SQLCODE.
Question What are the steps involved in Database Shutdown?
Answer Close the Database, Dismount the Database and Shutdown theInstance.
Question What are the steps involved in Database Startup?
Answer Start an instance, Mount the Database and Open theDatabase.
Question What are the steps involved in Instance Recovery?
Answer Rolling forward to recover data that has not been recorded in datafiles, yet has
been recorded in the on-line redo log, including the contents ofrollback segments.
Rolling back transactions that have been explicitly rolled back or havenot been
committed as indicated by the rollback segments regenerated in step a.Releasing any
resources (locks) held by transactions in process at the time ofthe failure. Resolving any
pending distributed transactions undergoing atwo-phase commit at the time of the
instance failure.
Question What are the two parts of aprocedure
Answer Procedure Specification and Procedure Body.
Question What are the types of DatabaseLinks
Answer Private Database Link, Public Database Link&Network DatabaseLink.
Question What are the types of SQLStatement
Answer Data Definition Language : CREATE, ALTER,DROP, TRUNCATE,
REVOKE,NO AUDIT&COMMIT.Data Manipulation Language: INSERT, UPDATE,
DELETE, LOCKTABLE,EXPLAIN PLAN&SELECT. Transactional Control:
COMMIT&ROLLBACKSession Control: ALTERSESSION&SET ROLESystem Control
:ALTER
SYSTEM.
Question What are the usage of SAVEPOINTS?
Answer SAVEPOINTS are used to subdivide a transaction into smaller parts.It enables
rolling back part of a transaction. Maximum of five save points areallowed.

Question What are the uses of RollbackSegment


Answer Rollback Segments are used : To generate read-consistent databaseinformation
during database recovery to rollback uncommitted transactions forusers.
Question What are two virtual tables available duringdatabase trigger execution ?
Answer The table columns are referred as OLD.column_name andNEW.column_name.
For triggers related to INSERT only NEW.column_name values onlyavailable. For
triggers related to UPDATE only OLD.column_name NEW.column_namevalues only
available. For triggers related to DELETE only OLD.column_name valuesonly available.
Question What are various constraints used inSQL?
Answer – NULL -NOT NULL –CHECK-DEFAULT
Question What are various joins used while writingSUBQUERIES?
Answer Self join-Its a join foreign key of a table references the sametable. Outer Join—
Its a join condition used where One can query all the rows ofone of the tables in the join
condition even though they don't satisfy the join condition.Equi-join--Its a join condition
that retrieves rows from one or more tables inwhich one or more columns in one table are
equal to one or more columns in thesecond table.
Question What are various privileges that a user cangrant to another user?
Answer-SELECT –CONNECT –RESOURCES
Question What does a Control file Contain?
Answer A Control file records the physical structure of the database. Itcontains the
following information. Database Name Names and locations of adatabase's files and
redolog files. Time stamp of database creation.
Question What does COMMIT do?
Answer COMMIT makes permanent the changes resulting from all SQLstatements in the
transaction. The changes made by the SQL statements of a transactionbecome visible to
other user sessions transactions that start only after transaction iscommitted.
Question What does ROLLBACK do?
Answer ROLLBACK retracts any of the changes resulting from the SQLstatements in the
transaction.
Question What is a cursor?
Answer Oracle uses work area to execute SQL statements and storeprocessing
information PL/SQL construct called a cursor lets you name a workarea and access its
stored information A cursor is a mechanism used to fetchmore than one row in a Pl/SQl
block.
Question What is a cursor for loop?
Answer Cursor For Loop is a loop where oracle implicitly declares a loopvariable, the
loop index that of the same record type as the cursor'srecord.
Question What is a Data Dictionary?
Answer The data dictionary of an ORACLE database is a set of tables andviews that are
used as a read-only reference about the database. It storesinformation about both the
logical and physical structure of the database, thevalid users of an ORACLE database,
integrity constraints defined for tables inthe database and space allocated for a schema
object and how much of it is beingused.
Question What is a Data File?
Answer Every ORACLE database has one or more physical data files. Adatabase's data
files contain all the database data. The data of logicaldatabase structures such as tables
and indexes is physically stored in the datafiles allocated for a database.
Question What is a Data Segment?
Answer Each Non-clustered table has a data segment. All of the table'sdata is stored in
the extents of its data segment. Each cluster has a data segment. Thedata of every table in
the cluster is stored in the cluster's datasegment.
Question What is a database link?
Answer Database Link is a named path through which a remote database canbe accessed.
Question What is a database trigger ? Name some usages ofdatabase trigger ?
Answer Database triggeris stored PL/SQL program unit associated with a specific
database table. Usagesare Audit data modifications, Log events transparently, Enforce
complex businessrules Derive column values automatically, Implement complex
securityauthorizations. Maintain replicate tables.
Question What is a deadlock ? Explain
Answer Two processes wating to update the rows of a table which arelocked by the other
process then deadlock arises. In a database environment thiswill often happen because of
not issuing proper row lock commands. Poor designof front-end application may cause
this situation and the performance of serverwill reduce drastically. These locks will be
released automatically when acommit/rollback operation performed or any one of this
processes being killedexternally.
Question What is a join ? Explain the different types ofjoins ?
Answer Join is a query which retrieves related columns or rows frommultiple tables. Self
Join -Joining the table with itself.Equi Join - Joiningtwo tables by equating two common
columns.Non-Equi Join - Joining two tables by equating two commoncolumns.Outer Join
– Joining two tables in such a way that query can alsoretrieve rows that do not have
corresponding join value in the othertable.
Question What is a Synonym?
Answer A synonym is an alias for a table, view, sequence or programunit.
Question What is a Private Synonyms?
Answer A Private Synonyms can be accessed only by the owner.
Question What is a Public Synonyms?
Answer Public synonyms can be accessed by any user on thedatabase.
Question What is a Redo Log
Answer The set of Redo Log files for a database is collectively known asthe database's
redo log.
Question What is a Segment?
Answer A segment is a set of extents allocated for a certain logicalstructure.
Question What is a Sequence?
Answer A sequence generates a serial list of unique numbers for numericalcolumns of a
database's tables.
Question What is aTablespace?
Answer A database is divided into Logical Storage Unit calledtablespaces. A tablespace is
used to grouped related logical structurestogether.
Question What is a Temporary Segment?
Answer Temporary segments are created by ORACLE when a SQL statementneeds a
temporary work area to complete execution. When the statement finishesexecution, the
temporary segment extents are released to the system for futureuse.
Question What is an Exception ? What are types ofException ?
Answer Exception is the error handling part of PL/SQL block. The typesare Predefined
and user defined. Some of Predefined exceptions are.CURSOR_ALREADY_OPEN
DUP_VAL_ON_INDEX NO_DATA_FOUND TOO_MANY_ROWS
INVALID_CURSORINVALID_NUMBER LOGON_DENIED NOT_LOGGED_ON
PROGRAM-ERROR STORAGE_ERROR TIMEOUT_ON_RESOURCE
VALUE_ERROR ZERO_DIVIDE OTHERS.
Question What is difference between SQL and SQL*PLUS?
Answer SQL*PLUS is a command line tool where as SQL and PL/SQL
languageinterface and reporting tool. Its a command line tool that allows user to typeSQL
commands to be executed directly against an Oracle database. SQL is alanguage
used to query the relational database(DML,DCL,DDL). SQL*PLUS commandsare
used to format query result, Set options, Edit SQL commands andPL/SQL.
Question What is difference between UNIQUE and PRIMARYKEY constraints?
Answer A table can have only one PRIMARY KEY whereas there can be anynumber of
UNIQUE keys. The columns that compose PK are automatically define NOTNULL,
whereas a column that compose a UNIQUE is not automatically defined to bemandatory
must also specify the column is NOT NULL.
Question What is difference between Rename andAlias?
Answer Rename is a permanent name given to a table or column whereasAlias is a
temporary name given to a table or column which do not exist once theSQL statement is
executed.
Question What is difference between CHAR and VARCHAR2 ?What is the
maximum SIZE allowed for each type?
Answer CHAR pads blank spaces to the maximum length. VARCHAR2 does notpad
blank spaces. For CHAR it is 255 and 2000 for VARCHAR2.
Question What is difference between a formal and anactual parameter?
Answer The variables declared in the procedure and which are passed, asarguments are
called actual, the parameters in the procedure declaration. Actualparameters contain the
values that are passed to a procedure and receive results. Formalparameters are the
placeholders for the values of actual parameters
Question What is difference between a Cursor declared ina procedure and Cursor
declared in a package specification?
Answer A cursor declared in a package specification is global and can beaccessed by
other procedures or procedures in a package. A cursor declared in aprocedure is local to
the procedure that can not be accessed by otherprocedures.
Question What is difference between % ROWTYPE and TYPERECORD ?
Answer % ROWTYPE is to be used whenever query returns a entire row of atable or
view. TYPE rec RECORD is to be used whenever query returns columns ofdifferent
table or views and variables. E.g. TYPE r_emp is RECORD (enoemp.empno%
type,ename emp ename %type ); e_rec emp% ROWTYPE
cursor c1 is select empno,deptno from emp; e_rec c1 %ROWTYPE.
Question What is Mirrored on-line RedoLog
Answer A mirrored on-line redo log consists of copies of on-line redo logfiles physically
located on separate disks, changes made to one member of the group aremade to all
members.
Question What is Network Database link?
Answer Network database link is created and managed by a network domainservice. A
network database link can be used when any user of any database inthe network specifies
a global object name in a SQL statement or objectdefinition.
Question What is Log Switch?
Answer The point at which ORACLE ends writing to one online redo log fileand begins
writing to another is called a log switch.
Question What is Index Cluster?
Answer A Cluster with an index on the Cluster Key.
Question What is Hash Cluster?
Answer A row is stored in a hash cluster based on the result of applyinga hash function to
the row's cluster key value. All rows with the same hash keyvalue are stores together on
disk.
Question What is Full Backup?
Answer A full backup is an operating system backup of all data files,on-line redo log files
and control file that constitute ORACLE database and theparameter.
Question What is Database Link?
Answer A database link is a named object that describes a "path" from onedatabase to
another.
Question What is Data Block?
Answer ORACLE database's data is stored in data blocks. One data blockcorresponds to
a specific number of bytes of physical database space ondisk.
Question What is CYCLE/NO CYCLE in aSequence
Answer CYCLE specifies that the sequence continues to generate valuesafter reaching
either maximum or minimum value. After pan ascending sequence reaches itsmaximum
value, it generates its minimum value. After a descending sequencereaches its minimum,
it generates its maximum. NO CYCLE specifies that thesequence cannot generate more
values after reaching its maximum or minimumvalue.
Question What is correlated sub-query?
Answer Correlated sub query is a sub query which has reference to themain query.
Question What is cluster Key?
Answer The related columns of the tables in a cluster is called theCluster Key.
Question What is Archived Redo Log?
Answer Archived Redo Log consists of Redo Log files that have archivedbefore being
reused.
Question What is an Integrity Constraint?
Answer Integrity constraint is a rule that restricts values to a columnin a table.
Question What is an Index?
Answer An Index is an optional structure associated with a table to havedirect access to
rows, which can be created to increase the performance of data retrieval.Index can be
created on one or more columns of a table.
Question What is an Extent?
Answer An Extent is a specific number of contiguous data blocks, obtainedin a single
allocation, and used to store a specific type of information.
Question What is a View?
Answer A view is a virtual table. Every view has a Query attached to it.(The Query is a
SELECT statement that identifies the columns and rows of thetable(s) the view uses.)
Question What is a transaction?
Answer Transaction is logical unit between two commits and commit androllback.
Question What is atimer?
Answer Timer is an "internal time clock" that you can programmaticallycreate to perform
an action each time the timer expires.

MEMORY MANAGEMENT
Const Data: The const data area stores string literals and other data whose values are
known at compile time. No objects of class type can exist in this area. All data in this
area is available during the entire lifetime of the program. Further, all of this data is read-
only, and the results of trying to modify it are undefined.

Stack: The stack stores automatic variables. Typically allocation is much faster than for
dynamic storage (heap or free store) because a memory allocation involves only pointer
increment rather than more complex management. Objects are constructed immediately
after memory is allocated and destroyed immediately before memory is deallocated, so
there is no opportunity for programmers to directly manipulate allocated but uninitialized
stack space.

Free Store: The free store is one of the two dynamic memory areas, allocated/freed by
new/delete. Object lifetime can be less than the time the storage is allocated; that is, free
store objects can have memory allocated without being immediately initialized, and can
be destroyed without the memory being immediately deallocated. During the period
when the storage is allocated but outside the object's lifetime, the storage may be
accessed and manipulated through a void* but none of the proto-object's nonstatic
members or member functions may be accessed, have their addresses taken, or be
otherwise manipulated.

Heap: The heap is the other dynamic memory area, allocated/freed by malloc / free and
their variants. Note that while the default global new and delete might be implemented in
terms of malloc and free by a particular compiler, the heap is not the same as free store
and memory allocated in one area cannot be safely deallocated in the other. Memory
allocated from the heap can be used for objects of class type by placement-new
construction and explicit destruction. If so used, the notes about free store object lifetime
apply similarly here.

Global/Static: Global or static variables and objects have their storage allocated at
program startup, but may not be initialized until after the program has begun executing.
For instance, a static variable in a function is initialized only the first time program
execution passes through its definition. The order of initialization of global variables
across translation units is not defined, and special care is needed to manage
dependencies between global objects (including class static’s). As always, uninitialized
Proto- objects' storage may be accessed and manipulated through a void* but no
nonstatic members or member functions may be used or referenced outside the object's
actual lifetime.
Automatic Storage
Local objects that are not explicitly declared static or extern, local objects that are
declared auto or register, and function arguments have automatic storage. This type of
storage is also called stack memory.

Static Storage

Global objects, static data members of a class, namespace variables, and static variables
in functions reside in static memory.

NOTE:

Static- storage allocated at link time, initialized at load time, and released on termination.
Stack- storage that is allocated, initialized, and released on a last in first out basis.
Heap- storage that can be dynamically allocated, initialized, and released.

WHERE IS A POINTER STORED?


A pointer can be stored in any of the same locations that any other variable can be stored
but is generally not stored on the heap. It can be defined and stored globally, or it can be
defined local to a function and stored on the stack. The size of the pointer depends on the
implementation and for 32 bit operating systems, it generally requires four bytes of
storage space. This is not a requirement however, a compiler writer can use any number
of bytes desired to store a pointer.

Keep in mind, a pointer is like any other variable in the sense that it requires storage
space somewhere in the computer's memory, but it is not like most variables because it
contains no data, only an address. Since it is an address, it actually contains a number
referring to some memory location.

Class Object Storage:

Static: In C++, the size of any object that is declared static can be determined at compile
time, and so storage for the object can be allocated by the linker. The object will be
created just before the program begins to execute, and will be destroyed just before the
program terminates. It is important to note that you have little or no control over the order
in which static objects are created or destroyed. (This can be a major source of portability
problems.)

Stack: In C++, an object that is declared directly is created on the stack. Objects are
destroyed in reverse order of creation. This is done automatically on exit of the block
they were created in.
Heap: Objects created with the new operator are placed on the heap. They will persist
until explicitly destroyed, or the program terminates. You cannot refer to such an object
directly, you need to use a pointer. Every object created with new should have a
corresponding delete, otherwise you will get memory leaks.

Calling Functions:
The parameters to procedure and function calls, and the return result are placed on the
stack. What is actually placed on the stack depends on the type of parameter. This is very
important to understand when it comes to passing objects to a procedure and returning
objects from a procedure. The default passing convention for parameters is by value. That
is, instead of the actual parameter, a copy of it is placed on the stack. The same holds for
the return value. A place is reserved for the return value on the stack, and when the return
is executed the value to be returned is copied into this place.

Passing a parameter by reference avoids the copying of values by putting a pointer to the
parameter on the stack. Returning by reference is similar

NOTE:
When the parameter appearing in the argument list is not of the correct type, such as
providing an int argument when a double is required, or having an expression in the
argument position. In that case a temporary object is created on the stack to store the
actual parameter. If that temporary object is being passed by const reference (it must be
const) then a pointer to the temporary is passed as the parameter.

Dynamic Memory Allocation


Memory allocation provides a way to dynamically create buffers and arrays. Dynamic
means that the space is allocated in memory as the program is executing. On many
occasions the sizes of objects will not be known until run time.

How to Allocate Memory With Malloc()


The standard library function malloc is commonly used to allocate memory. Its prototype
is:

void *malloc (size_t nbytes);

Malloc returns a void pointer to the allocated buffer. This pointer must be cast into the
proper type to access the data to be stored in the buffer. On failure, malloc returns a null
pointer.

How to Free Memory With Free ()


When using dynamically allocated memory, it is necessary for the programmer to free the
memory after its use.

void free (void *pt);


It is not necessary to cast the pointer argument back to void. The compiler handles this
conversion.

Disadvantage of New:
One disadvantage of New is that there is no way to reallocate memory. With Malloc you
can use Realloc to extend the amount of memory quickly. With New you have to create a
new chunk of memory with the modified size and then copy over the data from the
original buffer and then delete the original buffer. This can be a slow process.

Mixing Memory Allocation:

Never use malloc () to allocate memory and then delete it. Likewise never use new to
allocate memory and then free() it. These are not compile time errors, but can cause
spectacular program crashes which again, are difficult to debug. Use the memory
allocation routines consistently.
Don't mix new /delete with C allocation/ deallocation functions, or the behavior is
undefined. Remember that new may throw exceptions (from failed memory allocation or
from constructor).

Can I free () pointers allocated with new? Can I delete pointers allocated with malloc ()?
NO
If you allocated via pointer = new char [nbytes], you must use delete [] p; you must not
use free (p). Or if you allocated via pointer = malloc (nbytes), you must use free (p); you
must not use delete [] p or delete p! Mixing these up could cause a catastrophic failure at
runtime if the code was ported to a new machine, a new compiler, or even a new version
of the same compiler.

Shallow Copies :
The default copy constructor and assignment operator make shallow copies.

Don't write a copy constructor if shallow copies are ok:


If the object has no pointers to dynamically allocated memory, a shallow copy is probably
sufficient. Therefore the default copy constructor, default assignment operator, and
default destructor are ok and you don't need to write your own.

Deep copies :
If an object has pointers to dynamically allocated memory, and the dynamically allocated
memory needs to be copied when the original object is copied, then a deep copy is
required.
A class that requires deep copies generally needs:
A constructor to either make an initial allocation or set the pointer to NULL.
A destructor to delete the dynamically allocated memory.
A copy constructor to make a copy of the dynamically allocated memory.
An overloaded assignment operator to make a copy of the dynamically allocated memory.
DATABASE Interview Questions

Question TRUNCATE TABLE EMP; DELETE FROM EMP;


Will the outputs of the above two commands differ?
Answer Both will result in deleting all the rows in the table EMP.
Question What are the privileges that can be granted on a table by a user to others?
Answer Insert, update, delete, select, references, index, execute, alter, all.
Question What command is used to get back the privileges offered by the GRANT
command?
Answer REVOKE.
Question What is the difference between TRUNCATE and DELETE commands?
Answer TRUNCATE is a DDL command whereas DELETE is a DML command. Hence
DELETE operation can be rolled back, but TRUNCATE operation cannot be rolled back.
WHERE clause can be used with DELETE and not with TRUNCATE.
Question What is the parameter substitution symbol used with INSERT INTO
command?
Answer&
Question What is the use of CASCADE CONSTRAINTS?
Answer When this clause is used with the DROP command, a parent table can be dropped
even when a child table exists.
Question What is the use of the DROP option in the ALTER TABLE command?
Answer It is used to drop constraints specified on the table.
Question Which command displays the SQL command in the SQL buffer, and then
executes it?
Answer RUN.
Question Which command executes the contents of a specified file?
Answer START or @.
Question Which date function is used to find the difference between two dates?
Answer MONTHS_BETWEEN.
Question Which function is used to find the largest integer less than or equal to a
specificvalue?
Answer FLOOR.
Question Which system table contains information on constraints on all the tables
created?
Answer USER_CONSTRAINTS.
Question Why does the following command give a compilation error?
DROP TABLE &TABLE_NAME;
Answer Variable names should start with an alphabet. Here the table name starts with an
'&' symbol.
To see current user name
Sql> show user;
Change SQL prompt name
SQL> set sqlprompt “sukhvir > “
sukhvir >
How do I display row number with records?
To achieve this use rownum pseudocolumn with query, like SQL> SQL> select rownum,
ename from emp;
Output:
1 sukhvir
2 nauhwar
Find out nthhighest salary from emp table
SELECT DISTINCT (a.sal) FROM EMP A WHERE&N = (SELECT COUNT
(DISTINCT (b.sal)) FROM EMP B WHEREa.sal<=b.sal);
Display Odd/ Evennumber of records
Odd number of records:
select * from emp where(rowid,1) in (select rowid, mod(rownum,2) from emp);
135
Even numberof records:
select * from emp where (rowid,0) in (select rowid,mod(rownum,2) from emp)
246
Any three PL/SQLExceptions?
Too_many_rows, No_Data_Found, Value_Error, Zero_Error,Others
What are PL/SQLCursor Exceptions?
Cursor_Already_Open, Invalid_Cursor
What is themaximum number of triggers, can apply to a single table?
12 triggers.
Question Can a function take OUT parameters. If notwhy?
Answer No. A function has to return a value, an OUT parameter cannotreturn a value.
Question Which is more faster - IN orEXISTS?
Answer EXISTS is more faster than IN because EXISTS returns a Booleanvalue whereas
IN returns a value.
Question Which datatype is used for storing graphics andimages?
Answer LONG RAW data type is used for storing BLOB's (binary largeobjects).
Question Wherethe integrity constraints are stored in Data Dictionary?
Answer The integrity constraints are stored inUSER_CONSTRAINTS.
Question When does a Transaction end?
Answer When it is committed or Rollbacked.
Question When do you use WHERE clause and when do you useHAVING clause?
Answer HAVING clause is used when you want to specify acondition for a group
function and it is written after GROUP BY clause. TheWHERE clause is used when you
want to specify a condition for columns, singlerow functions except group functions and
it is written before GROUP BY clause ifit is used.
Question When can Hash Cluster used?
Answer Hash clusters are better choice when a table is often queried withequality queries.
For such queries the specified cluster key value is hashed.The resulting hash key value
points directly to the area on disk that stores thespecified rows.
Question What will happen after commitstatement
Answer Cursor C1 is Select empno, ename from emp; Begin open C1;loop
Fetch C1 into eno.ename; Exit When C1 %notfound;----- commit;
end loop; end; The cursor having query as SELECT .... FOR UPDATE getsclosed after
COMMIT/ROLLBACK. The cursor havingquery as SELECT.... does not
get closed even after COMMIT/ROLLBACK.
Question What WHERE CURRENT OF clause does in acursor?
Answer LOOP SELECT num_credits INTO v_numcredits FROM
Classes WHERE dept=123 and course=101; UPDATE students SETcurrent_credits=
current_credits+v_numcredits WHERE CURRENT OF X; END LOOPCOMMIT; END;
Question What should be the return type for a cursorvariable. Can we use a scalar
data type as returntype?
Answer The return type for a cursor must be a record type. It can bedeclared explicitly as
a user-defined or %ROWTYPE can be used. eg TYPEt_studentsref IS REF CURSOR
RETURN students%ROWTYPE
Question What is use of a cursor variable? How it isdefined?
Answer A cursor variable is associated with different statements at runtime, which can
hold different values at run time. Static cursors can only beassociated with one run time
query. A cursor variable is reference type (like apointer in C). Declaring a cursor variable:
TYPE type_name IS REF CURSOR RETURNreturn_type type_name is the name of the
reference type,return_type is a recordtype indicating the types of the select list that will
eventually be returned bythe cursor variable.
Question What is trigger associated with the timer?
Answer When-timer-expired.
Question What is the use of Redo LogInformation
Answer The Information in a redo log file is used only to recover thedatabase from a
system or media failure prevents database data from beingwritten to a database's data
files.
Question What is the use of Control File?
Answer When an instance of an ORACLE database is started, its controlfile is used to
identify the database and redo log files that must be opened fordatabase operation to
proceed. It is also used in database recovery.
Question What is the Subquery?
Answer Sub query is a query whose return values are used in filteringconditions of the
main query.
Question What is the purpose of acluster?
Answer Oracle does not allow a user to specifically locate tables, sincethat is a part
of the function of the RDBMS. However, for the purpose of increasingperformance,
oracle allows a developer to create a CLUSTER. A CLUSTER provides ameans for
storing data from different tables together for faster retrieval thanif the table placement
were left to the RDBMS.
Question What is the maximum number of CHECK constraintsthat can be defined
on a column?
Answer No Limit.
Question What isthe function of Redo Log?
Answer The Primary function of the redo log is to recordall changes made to
data.Question Whatis the fastest way of accessing a row in a table?
Answer Using ROWID.CONSTRAINTS
Question What is the basic structure ofPL/SQL
Answer PL/SQL uses block structure as its basic structure. Anonymousblocks or nested
blocks can be used in PL/SQL.
Question What is Table ?
Answer A table is the basic unit of data storage in an ORACLE database.The tables of a
database hold all of the user accessible data. Table data isstored in rows and columns.
Question What is SYSTEM tablespace and when is itCreated?
Answer Every ORACLE database contains a tablespace named SYSTEM, which
isautomatically created when the database is created. The SYSTEM tablespace
alwayscontains the data dictionary tables for the entire database.
Question What is self-referential integrity constraint?
Answer If a foreign key reference a parent key of the same table is called self-referential
integrity constraint.
Question What isschema?
Answer A schema is collection of database objects of a User.
Question What is ROWID ?
Answer ROWID is a pseudo column attached to each row of a table. It is 18character
long, blockno, rownumber are the components of ROWID.
Question What is Row Chaining?
Answer In Circumstances, all of the data for a row in a table may notbeable to fit in the
same data block. When this occurs , the data for the row is stored in achain of data block
(one or more) reserved for that segment.
Question What is Rollback Segment?
Answer A Database contains one or more Rollback Segments to temporarilystore "undo"
information.
Question What is Restricted Mode of Instance Startup?
Answer An instance can be started in (or later altered to be in)restricted mode so that
when the database is open connections are limited onlyto those whose user accounts have
been granted the RESTRICTED SESSION systemprivilege.
Question What is Referential Integrity?
Answer Maintaining data integrity through a set of rules that restrictthe values of one or
more columns of the tables based on the values of primarykey or unique key of the
referenced table.
Question What is Read-Only Transaction?
Answer A Read-Only transaction ensures that the results of each queryexecuted in the
transaction are consistant with respect to the same point intime.
Question What is Raise_application_error?
Answer Raise_application_error is a procedure of package DBMS_STANDARDwhich
allows to issue an user_defined error messages from stored sub-program ordatabase
trigger.
Question What is Public Database Link?
Answer Public database link is created for the special user group PUBLIC.A public
database link can be used when any user in the associated databasespecifies a global
object name in a SQL statement or objectdefinition.
Question What is Private Database Link?
Answer Private database link is created on behalf of a specific user. Aprivate database
link can be used only when the owner of the link specifies aglobal object name in a SQL
statement or in the definition of the owner's views orprocedures.
Question What is Pragma EXECPTION_INIT ? Explain theusage ?
Answer The PRAGMA EXECPTION_INIT tells the complier to associate anexception
with an oracle error. To get an error message of a specific oracleerror. e.g. PRAGMA
EXCEPTION_INIT (exception name, oracle errornumber)
Question What is PL/SQL table?
Answer Objects of type TABLE are called "PL/SQL tables", which aremodeled as (but
not the same as) database tables, PL/SQL tables use a primaryPL/SQL tables can have
one column and a primary key. Cursors
Question What is PL/SQL?
Answer PL/SQL is a procedural language that has both interactive SQL andprocedural
programming language constructs such as iteration, conditionalbranching.
Question What is Partial Backup?
Answer A Partial Backup is any operating system backup short of a fullbackup, taken
while the database is open or shut down.
Question What is Parallel Server?
Answer Multiple instances accessing the same database (Only In Multi-
CPUenvironments)
Question What is Overloading ofprocedures
Answer The Same procedure name is repeated with parameters of differentdatatypes and
parameters in different positions, varying number of parameters iscalled overloading of
procedures. e.g. DBMS_OUTPUT put_line
Question What is On-line RedoLog?
Answer The On-line Redo Log is a set of tow or more on-line redo filesthat record all
committed changes made to the database. Whenever a transaction iscommitted, the
corresponding redo entries temporarily stores in redo log buffersof the SGA are written to
an on-line redo log file by the background processLGWR. The on-line redo log files are
used in cyclical fashion.
Question What is ON DELETE CASCADE?
Answer When ON DELETE CASCADE is specified ORACLE maintains
referentialintegrity by automatically removing dependent foreign key values if a
referencedprimary or unique key value is removed.
Question Can a primary key contain more than one columns?
Answer Yes
Question Can a Tablespace hold objects from differentSchemes ?
Answer Yes.
Question Can a View based on another View?
Answer Yes.
Question Can a view be updated/inserted/deleted? If Yesunder what conditions ?
Answer A View can be updated/deleted/inserted if it has only one basetable if the view is
based on columns from one or more tables then insert,update and delete is not possible.
Question Can an Integrity Constraint be enforced on atable if some existing table
data does not satisfy the constraint?
Answer No.
Question Can Full Backup be performed when the databaseis open ?
Answer No.
Question Can objects of the same Schema reside indifferent tablespaces.?
Answer Yes.
Question What is an Index Segment?
Answer Each Index has an Index segment that stores all of its data.
Question Can the default values be assigned to actualparameters?
Answer Yes
Question Can you use a commit statement within a databasetrigger?
Answer No
Question Describe Referential Integrity?
Answer A rule defined on a column (or set of columns) in one table thatallows the insert
or update of a row only if the value for the column or set ofcolumns (the dependent
value) matches a value in a column of a related table(the referenced value). It also
specifies the type of data manipulation allowedon referenced data and the action to be
performed on dependent data as a result of any action on referenced data.
Question Difference between an implicit&an explicitcursor
Answer PL/SQL declares a cursor implicitly for all SQL data manipulationstatements,
including quries that return only one row. However, queries thatreturn more than one row
you must declare an explicit cursor or use a cursor FORloop. Explicit cursor is a cursor in
which the cursor name is explicitlyassigned to a SELECT statement via the
CURSOR...IS statement. An implicit cursoris used for all SQL statements Declare, Open,
Fetch, Close. An explicit cursorsare used to process multirow SELECT statements An
implicit cursor is used toprocess INSERT, UPDATE, DELETE and single row
SELECT. .INTO statements.
Question Difference between database triggers and formtriggers?
Answer- Data base trigger(DBT) fires when a DML operation is performed ona data base
table. Form trigger(FT) Fires when user presses a key or navigatesbetween fields on the
screen -Can be row level or statement level No distinctionbetween row level and
statement level. -Canmanipulate data stored in Oracle tables via SQLCan manipulate
data in Oracle tables as well as variables in forms. -Can befired from any session
executing the triggering DML statements. Can be firedonly from the form that define the
trigger. -Can cause other database triggersto fire.Can cause other database triggers to fire,
but not other form triggers.
Question Difference between NO DATA FOUND and%NOTFOUND
Answer NO DATA FOUND is an exception raised only for the
SELECT....INTOstatements when the where clause of the querydoes not match any rows.
When thewhere clause of the explicit cursor does not match any rows the
%NOTFOUNDattribute is set to TRUE instead.
Question Difference between procedure andfunction
Answer Functions are named PL/SQL blocks that return a value and can becalled with
arguments procedure a named block that can be called with parameter.A procedure all is a
PL/SQL statement by itself, while a Function call is calledas part of an expression.
Question Difference between SUBSTR and INSTR?
Answer INSTR (String1,String2(n,(m)),INSTR returns the position of themth occurrence
of the string 2 instring1. The search begins from nth position ofstring1.SUBSTR (String1
n,m)SUBSTR returns a character string of size m in string1, starting fromnth position of
string1.
Question Display the number value inWords?
Answer SQL>select sal, (to_char(to_date(sal,'j'), 'jsp')) from emp;the output like,
SAL (TO_CHAR(TO_DATE(SAL,'J'),'JSP'))
----------------------------------------------
800 eight hundred
1600 one thousand six hundred
1250 one thousand two hundred fifty
If you want to add some text like, Rs. Three Thousand only. SQL>select sal "Salary ",
(' Rs. '|| (to_char(to_date(sal,'j'), 'Jsp'))|| ' only.')) "Sal in Words"from emp /
Salary Sal in Words--------------------------------------------------
800 Rs. Eight Hundred only.
1600 Rs. One Thousand Six Hundred only.
1250 Rs. One Thousand Two Hundred Fifty only.
Question Do View contain Data ?
Answer Views do not contain or store data.
Question Explain how procedures and functions are calledin a PL/SQL block ?
Answer Function is called as part of an expression. sal := calculate_sal('a822');
procedure is called as a PL/SQL statement calculate_bonus('A822');
Question Explain the relationship among Database,Tablespace and Data file.
Answer Each databases logically divided into one or more tablespaces oneor more data
files are explicitly created for each tablespace.
Question Explain UNION,MINUS,UNION ALL, INTERSECT
Answer INTERSECT returns all distinct rows selected by both queries.MINUS - returns
all distinct rows selected by the first query but not by thesecond. UNION - returns all
distinct rows selected by either query UNION ALL –returns all rows selected by either
query, including all duplicates.
Question Find out nth highest salary from emptable
Answer SELECT DISTINCT (a.sal) FROM EMP A WHERE&N = (SELECT
COUNT(DISTINCT (b.sal)) FROM EMP B WHERE a.sal<=b.sal); For Eg:-
Enter value for n: 2 SAL
---------
3700
Question Give the structure of the function?
Answer FUNCTION name (argument list .....) Return datatype is localvariable
declarations Begin executable statements Exception execution handlersEnd;

Question Give the structure of theprocedure


Answer PROCEDURE name (parameter list.....) is local variabledeclarations BEGIN
Executable statements. Exception. exception handlersend;
Question How are Indexes Update?
Answer Indexes are automatically maintained and used by ORACLE. Changesto table
data are automatically incorporated into all relevantindexes.
Question How do you find the numbert of rows in a Table?
Answer A bad answer is count them (SELECT COUNT(*) FROM table_name) Agood
answer is :- 'By generating SQL to ANALYZE TABLE table_name COUNTSTATISTICS
by querying Oracle System Catalogues (e.g. USER_TABLES orALL_TABLES). The
best answer is to refer to the utility which Oracle releasedwhich makes it unnecessary to
do ANALYZE TABLE for each Tableindividually.
How many LONG columns are allowed in a table ? Is itpossible to use LONG
columns in WHERE clause or ORDER BY?
Answer Only one LONG columns is allowed. It is not possible to use LONGcolumn in
WHERE or ORDER BY clause.
Question How many types of database triggers can bespecified on a table ? What
are they ?
Answer Insert Update Delete Before Row o.k. o.k. o.k. After Row o.k. o.k.o.k.
Before Statement o.k. o.k. o.k. After Statement o.k. o.k. o.k. If FOREACH ROW clause
is specified, then the trigger for each Row affected by thestatement. If WHEN clause is
specified, the trigger fires according to thereturned Boolean value.
Question How to access the current value and next valuefrom a sequence ? Is it
possible to access the current value in a session beforeaccessing next value ?
Answer Sequence name CURRVAL, Sequence nameNEXTVAL. It is not possible.Only if
you access next value in the session, current value can beaccessed.
Question How to define Data Block size?
Answer A data block size is specified for each ORACLE database when thedatabase is
created. A database users and allocated free database space inORACLE datablocks. Block
size is specified in INIT.ORA file and can’t be changedlatter.
Question How will you a activate/deactivate integrity constraints?
Answer The integrity constraints can be enabled or disabled by ALTERTABLE ENABLE
constraint/DISABLE constraint.
How will you delete duplicating rows from a base table?
Answer delete from table_name where rowid not in (select max(rowid) fromtable group
by duplicate_values_field_name); or deleteduplicate_values_field_name dv from
table_name ta where rowid<(select min(rowid) from table_name tb whereta.dv=tb.dv);
Question How you open and close a cursor variable. Why itis required?
Answer OPEN cursor variable FOR SELECT...Statement CLOSE cursor variableIn order
to associate a cursor variable with a particular SELECT statement OPENsyntax is used.
In order to free the resources used for the query CLOSEstatement is used.
Question How you were passing cursor variables in PL/SQL2.2?
Answer In PL/SQL 2.2 cursor variables cannot be declared in a package.This is because
the storage for a cursor variable has to be allocated usingPro*C or OCI with version 2.2,
the only means of passing a cursor variable to a PL/SQL block is via bindvariable or a
procedure parameter.
Question How you will avoid duplicating records in aquery?
Answer By using DISTINCT
Question How you will avoid your query from usingindexes?
Answer SELECT * FROM emp Where emp_no+' '=12345; i.e you have toconcatenate
the column name with space within codes in the where condition.SELECT /*+ FULL(a)
*/ ename, emp_no from emp where emp_no=1234; i.e usingHINTS
Question If a View on a single base table is manipulatedwill the changes be reflected
on the base table?
Answer If changes are made to the tables which are base tables of a viewwill the changes
be reference on the view.
Question If an unique key constraint on DATE column iscreated, will it validate the
rows that are inserted with SYSDATE?
Answer It won't, Because SYSDATE format contains time attached withit.
Question Is it possible to use Transaction controlStatements such a ROLLBACK or
COMMIT in Database Trigger ? Why?
Answer It is not possible. As triggers are defined for each table, if youuse COMMIT of
ROLLBACK in a trigger, it affects logical transaction processing.
Question min value. sql Select the Nth lowest value froma table
Answer select level, min('col_name') from my_table where level = '&n'connect by prior
('col_name')<'col_name') group by level; Example: Given a tablecalled emp with the
following columns: -- id number -- name varchar2(20) -- salnumber --
-- For the second lowest salary: -- select level, min(sal) fromemp
-- where level=2 -- connect by prior sal<sal -- group by level
Question Name the tables where characteristics of Package, procedure andfunctions are
stored
Answer User_objects, User_Source and User_error.
Question Suppose a customer table is having differentcolumns like customer no,
payments. What will be the query to select top three maxpayments?
Answer SELECT customer_no, payments from customer C1 WHERE
3<=(SELECTCOUNT(*) from customer C2 WHERE C1.payment<= C2.payment)
Question There is a % sign in one field of a column. Whatwill be the query to find
it?
Answer'' Should be used before '%'.
Question What a SELECT FOR UPDATE cursorrepresent.
Answer SELECT......FROM......FOR......UPDATE[OF column-reference][NOWAIT]The
processing done in a fetch loop modifies the rows that have been retrievedby the
cursor. A convenient way of modifying the rows is done by a method withtwo parts: the
FOR UPDATE clause in the cursor declaration, WHERE CURRENT OFCLAUSE
in an UPDATE or declaration statement.
Question What are advantages fo StoredProcedures
Answer Extensibility, Modularity, Reusability, Maintainability and onetime compilation.
Question What are Clusters?
Answer Clusters are groups of one or more tables physically storestogether to share
common columns and are often used together.
Question What are cursor attributes?
Answer- %ROWCOUNT -%NOTFOUND -%FOUND-%ISOPEN
Question What are different modes of parameters used infunctions and procedures?
Answer- IN -OUT -INOUT
Question What are different Oracle databaseobjects?
Answer- TABLES –VIEWS –INDEXES –SYNONYMS –SEQUENCES
-TABLESPACESetc
Question What are ORACLE PRECOMPILERS?
Answer Using ORACLE PRECOMPILERS, SQL statements and PL/SQL blocks can
becontained inside 3GL programs written in C,C++,COBOL,PASCAL, FORTRAN,PL/1
ANDADA. The Precompilers are known as Pro*C,Pro*Cobol,... This form of PL/SQL
isknown as embedded pl/sql,the language in which pl/sql is embedded is known asthe
host language. The prcompiler translates the embedded SQL and pl/sqlststements into
calls to the precompiler runtime library.The output must becompiled and linked with this
library to creater an executable.
Question What are Schema Objects?
Answer Schema objects are the logical structures that directly refer tothe database's data.
Schema objects include tables, views, sequences, synonyms, indexes,clusters, database
triggers, procedures, functions packages and databaselinks.
Question What are the advantages of operating a databasein ARCHIVELOG mode
over operating it in NO ARCHIVELOG mode?
Answer Complete database recovery from disk failure is possible only inARCHIVELOG
mode. Online database backup is possible only in ARCHIVELOGmode.
Question What are the advantages of Views?
Answer Provide an additional level of table security, by restrictingaccess to a
predetermined set of rows and columns of a table. Hide data complexity.Simplify
commands for the user. Present the data in a different perspective fromthat of the base
table. Store complex queries.
Question What are the Characteristics of Data Files?
Answer A data file can be associated with only one database. Once createda data file can't
change size. One or more data files form a logical unit ofdatabase storage called a
tablespace.
Question What are the components of a PL/SQL Block?
Answer Declarative part, Executable part and Exception part. DatatypesPL/SQL
Question What arethe components of Logical database structure of ORACLE
database?
Answer Tablespaces and the Database's Schema Objects.
Question What are the components of Physical databasestructure of Oracle
Database?
Answer ORACLE database is comprised of three types of files. One or moreData files,
two are more Redo Log files, and one or more Controlfiles.
Question What are the data types allowed in a table?
Answer CHAR,VARCHAR2,NUMBER,DATE,RAW,LONG and LONG RAW.
Question What are the different modes of mounting aDatabase with the Parallel
Server ?
Answer Exclusive Mode If the first instance that mounts a database doesso in exclusive
mode, only that Instance can mount the database. Parallel ModeIf the first instance that
mounts a database is started in parallel mode, otherinstances that are started in parallel
mode can also mount thedatabase.
Question What are the different type ofSegments
Answer Data Segment, Index Segment, Rollback Segment and TemporarySegment.
Question What are the Limitations of a CHECK Constraint?
Answer The condition must be a Boolean expression evaluated using thevalues in the row
being inserted or updated and can't contain sub queries,sequence, the
SYSDATE,UID,USER or USERENV SQL functions, or the pseudocolumns
LEVEL or ROWNUM.
Question What are the Referential actions supported byFOREIGN KEY integrity
constraint
Answer UPDATE and DELETE Restrict - A referential integrity rule thatdisallows the
update or deletion of referenced data. DELETE Cascade - When areferenced row is
deleted all associated dependent rows are deleted.
Question What are the return values of functions SQLCODEand SQLERRM ?
Answer SQLCODE returns the latest code of the error that has occurred.SQLERRM
returns the relevant error message of the SQLCODE.
Question What are the steps involved in Database Shutdown?
Answer Close the Database, Dismount the Database and Shutdown theInstance.
Question What are the steps involved in Database Startup?
Answer Start an instance, Mount the Database and Open theDatabase.
Question What are the steps involved in Instance Recovery?
Answer Rolling forward to recover data that has not been recorded in datafiles, yet has
been recorded in the on-line redo log, including the contents ofrollback segments.
Rolling back transactions that have been explicitly rolled back or havenot been
committed as indicated by the rollback segments regenerated in step a.Releasing any
resources (locks) held by transactions in process at the time ofthe failure. Resolving any
pending distributed transactions undergoing atwo-phase commit at the time of the
instance failure.
Question What are the two parts of aprocedure
Answer Procedure Specification and Procedure Body.
Question What are the types of DatabaseLinks
Answer Private Database Link, Public Database Link&Network DatabaseLink.
Question What are the types of SQLStatement
Answer Data Definition Language : CREATE, ALTER,DROP, TRUNCATE,
REVOKE,NO AUDIT&COMMIT.Data Manipulation Language: INSERT, UPDATE,
DELETE, LOCKTABLE,EXPLAIN PLAN&SELECT. Transactional Control:
COMMIT&ROLLBACKSession Control: ALTERSESSION&SET ROLESystem Control
:ALTER
SYSTEM.
Question What are the usage of SAVEPOINTS?
Answer SAVEPOINTS are used to subdivide a transaction into smaller parts.It enables
rolling back part of a transaction. Maximum of five save points areallowed.

Question What are the uses of RollbackSegment


Answer Rollback Segments are used : To generate read-consistent databaseinformation
during database recovery to rollback uncommitted transactions forusers.
Question What are two virtual tables available duringdatabase trigger execution ?
Answer The table columns are referred as OLD.column_name andNEW.column_name.
For triggers related to INSERT only NEW.column_name values onlyavailable. For
triggers related to UPDATE only OLD.column_name NEW.column_namevalues only
available. For triggers related to DELETE only OLD.column_name valuesonly available.
Question What are various constraints used inSQL?
Answer – NULL -NOT NULL –CHECK-DEFAULT
Question What are various joins used while writingSUBQUERIES?
Answer Self join-Its a join foreign key of a table references the sametable. Outer Join—
Its a join condition used where One can query all the rows ofone of the tables in the join
condition even though they don't satisfy the join condition.Equi-join--Its a join condition
that retrieves rows from one or more tables inwhich one or more columns in one table are
equal to one or more columns in thesecond table.
Question What are various privileges that a user cangrant to another user?
Answer-SELECT –CONNECT –RESOURCES
Question What does a Control file Contain?
Answer A Control file records the physical structure of the database. Itcontains the
following information. Database Name Names and locations of adatabase's files and
redolog files. Time stamp of database creation.
Question What does COMMIT do?
Answer COMMIT makes permanent the changes resulting from all SQLstatements in the
transaction. The changes made by the SQL statements of a transactionbecome visible to
other user sessions transactions that start only after transaction iscommitted.
Question What does ROLLBACK do?
Answer ROLLBACK retracts any of the changes resulting from the SQLstatements in the
transaction.
Question What is a cursor?
Answer Oracle uses work area to execute SQL statements and storeprocessing
information PL/SQL construct called a cursor lets you name a workarea and access its
stored information A cursor is a mechanism used to fetchmore than one row in a Pl/SQl
block.
Question What is a cursor for loop?
Answer Cursor For Loop is a loop where oracle implicitly declares a loopvariable, the
loop index that of the same record type as the cursor'srecord.
Question What is a Data Dictionary?
Answer The data dictionary of an ORACLE database is a set of tables andviews that are
used as a read-only reference about the database. It storesinformation about both the
logical and physical structure of the database, thevalid users of an ORACLE database,
integrity constraints defined for tables inthe database and space allocated for a schema
object and how much of it is beingused.
Question What is a Data File?
Answer Every ORACLE database has one or more physical data files. Adatabase's data
files contain all the database data. The data of logicaldatabase structures such as tables
and indexes is physically stored in the datafiles allocated for a database.
Question What is a Data Segment?
Answer Each Non-clustered table has a data segment. All of the table'sdata is stored in
the extents of its data segment. Each cluster has a data segment. Thedata of every table in
the cluster is stored in the cluster's datasegment.
Question What is a database link?
Answer Database Link is a named path through which a remote database canbe accessed.
Question What is a database trigger ? Name some usages ofdatabase trigger ?
Answer Database triggeris stored PL/SQL program unit associated with a specific
database table. Usagesare Audit data modifications, Log events transparently, Enforce
complex businessrules Derive column values automatically, Implement complex
securityauthorizations. Maintain replicate tables.
Question What is a deadlock ? Explain
Answer Two processes wating to update the rows of a table which arelocked by the other
process then deadlock arises. In a database environment thiswill often happen because of
not issuing proper row lock commands. Poor designof front-end application may cause
this situation and the performance of serverwill reduce drastically. These locks will be
released automatically when acommit/rollback operation performed or any one of this
processes being killedexternally.
Question What is a join ? Explain the different types ofjoins ?
Answer Join is a query which retrieves related columns or rows frommultiple tables. Self
Join -Joining the table with itself.Equi Join - Joiningtwo tables by equating two common
columns.Non-Equi Join - Joining two tables by equating two commoncolumns.Outer Join
– Joining two tables in such a way that query can alsoretrieve rows that do not have
corresponding join value in the othertable.
Question What is a Synonym?
Answer A synonym is an alias for a table, view, sequence or programunit.
Question What is a Private Synonyms?
Answer A Private Synonyms can be accessed only by the owner.
Question What is a Public Synonyms?
Answer Public synonyms can be accessed by any user on thedatabase.
Question What is a Redo Log
Answer The set of Redo Log files for a database is collectively known asthe database's
redo log.
Question What is a Segment?
Answer A segment is a set of extents allocated for a certain logicalstructure.
Question What is a Sequence?
Answer A sequence generates a serial list of unique numbers for numericalcolumns of a
database's tables.
Question What is aTablespace?
Answer A database is divided into Logical Storage Unit calledtablespaces. A tablespace is
used to grouped related logical structurestogether.
Question What is a Temporary Segment?
Answer Temporary segments are created by ORACLE when a SQL statementneeds a
temporary work area to complete execution. When the statement finishesexecution, the
temporary segment extents are released to the system for futureuse.
Question What is an Exception ? What are types ofException ?
Answer Exception is the error handling part of PL/SQL block. The typesare Predefined
and user defined. Some of Predefined exceptions are.CURSOR_ALREADY_OPEN
DUP_VAL_ON_INDEX NO_DATA_FOUND TOO_MANY_ROWS
INVALID_CURSORINVALID_NUMBER LOGON_DENIED NOT_LOGGED_ON
PROGRAM-ERROR STORAGE_ERROR TIMEOUT_ON_RESOURCE
VALUE_ERROR ZERO_DIVIDE OTHERS.
Question What is difference between SQL and SQL*PLUS?
Answer SQL*PLUS is a command line tool where as SQL and PL/SQL
languageinterface and reporting tool. Its a command line tool that allows user to typeSQL
commands to be executed directly against an Oracle database. SQL is alanguage
used to query the relational database(DML,DCL,DDL). SQL*PLUS commandsare
used to format query result, Set options, Edit SQL commands andPL/SQL.
Question What is difference between UNIQUE and PRIMARYKEY constraints?
Answer A table can have only one PRIMARY KEY whereas there can be anynumber of
UNIQUE keys. The columns that compose PK are automatically define NOTNULL,
whereas a column that compose a UNIQUE is not automatically defined to bemandatory
must also specify the column is NOT NULL.
Question What is difference between Rename andAlias?
Answer Rename is a permanent name given to a table or column whereasAlias is a
temporary name given to a table or column which do notexist once theSQL statement is
executed.
Question What is difference between CHAR and VARCHAR2 ?What is the
maximum SIZE allowed for each type?
Answer CHAR pads blank spaces to the maximum length. VARCHAR2 does notpad
blank spaces. For CHAR it is 255 and 2000 for VARCHAR2.
Question What is difference between a formal and anactual parameter?
Answer The variables declared in the procedure and which are passed, asarguments are
called actual, the parameters in the procedure declaration. Actualparameters contain the
values that are passed to a procedure and receive results. Formalparameters are the
placeholders for the values of actual parameters
Question What is difference between a Cursor declared ina procedure and Cursor
declared in a package specification?
Answer A cursor declared in a package specification is global and can beaccessed by
other procedures or procedures in a package. A cursor declared in aprocedure is local to
the procedure that can not be accessed by otherprocedures.
Question What is difference between % ROWTYPE and TYPERECORD ?
Answer % ROWTYPE is to be used whenever query returns a entire row of atable or
view. TYPE rec RECORD is to be used whenever query returns columns ofdifferent
table or views and variables. E.g. TYPE r_emp is RECORD (enoemp.empno%
type,ename emp ename %type ); e_rec emp% ROWTYPE
cursor c1 is select empno,deptno from emp; e_rec c1 %ROWTYPE.
Question What is Mirrored on-line RedoLog
Answer A mirrored on-line redo log consists of copies of on-line redo logfiles physically
located on separate disks, changes made to one member of the group aremade to all
members.
Question What is Network Database link?
Answer Network database link is created and managed by a network domainservice. A
network database link can be used when any user of any database inthe network specifies
a global object name in a SQL statement or objectdefinition.
Question What is Log Switch?
Answer The point at which ORACLE ends writing to one online redo log fileand begins
writing to another is called a log switch.
Question What is Index Cluster?
Answer A Cluster with an index on the Cluster Key.
Question What is Hash Cluster?
Answer A row is stored in a hash cluster based on the result of applyinga hash function to
the row's cluster key value. All rows with the same hash keyvalue are stores together on
disk.
Question What is Full Backup?
Answer A full backup is an operating system backup of all data files,on-line redo log files
and control file that constitute ORACLE database and theparameter.
Question What is Database Link?
Answer A database link is a named object that describes a "path" from onedatabase to
another.
Question What is Data Block?
Answer ORACLE database's data is stored in data blocks. One data blockcorresponds to
a specific number of bytes of physical database space ondisk.
Question What is CYCLE/NO CYCLE in aSequence
Answer CYCLE specifies that the sequence continues to generate valuesafter reaching
either maximum or minimum value. After pan ascending sequence reaches itsmaximum
value, it generates its minimum value. After a descending sequencereaches its minimum,
it generates its maximum. NO CYCLE specifies that thesequence cannot generate more
values after reaching its maximum or minimumvalue.
Question What is correlated sub-query?
Answer Correlated sub query is a sub query which has reference to themain query.
Question What is cluster Key?
Answer The related columns of the tables in a cluster is called theCluster Key.
Question What is Archived Redo Log?
Answer Archived Redo Log consists of Redo Log files that have archivedbefore being
reused.
Question What is an Integrity Constraint?
Answer Integrity constraint is a rule that restricts values to a columnin a table.
Question What is an Index?
Answer An Index is an optional structure associated with a table to havedirect access to
rows, which can be created to increase the performance of data retrieval.Index can be
created on one or more columns of a table.
Question What is an Extent?
Answer An Extent is a specific number of contiguous data blocks, obtainedin a single
allocation, and used to store a specific type of information.
Question What is a View?
Answer A view is a virtual table. Every view has a Query attached to it.(The Query is a
SELECT statement that identifies the columns and rows of thetable(s) the view uses.)
Question What is a transaction?
Answer Transaction is logical unit between two commits and commit androllback.
Question What is atimer?
Answer Timer is an "internal time clock" that you can programmaticallycreate to perform
an action each time the timer expires.
Constructors
When an object of a class is created, C++ calls the constructor for that class.
If no constructor is defined, C++ invokes a default constructor, which
allocates memory for the object, but doesn't initialize it.

Why you should define a constructor

Uninitialized member fields have garbage in them. This creates the possibility
of a serious bug (eg, an uninitialized pointer, illegal values, inconsistent
values, ...).

Declaring a constructor

A constructor is similar to a function, but with the following differences.


• No return type.
• No return statement.

Example [extracts from three different files].


//=== point/point.h
=================================================
#ifndef POINT_H
#define POINT_H
class Point {
public:
Point(); // parameterless default constructor
Point(int new_x, int new_y); // constructor with parameters
int getX();
int getY();
private:
int x;
int y;
};
#endif

Here is part of the implementation file.


//=== point/point.cpp ==============================================
. . .
Point::Point() { // default constructor
x = 0;
y = 0;
}

Point::Point(int new_x, int new_y) { // constructor


x = new_x;
y = new_y;
}
. . .

And here is part of a file that uses the Point class.


//=== point/main.cpp ==============================================
. . .
Point p; // calls our default constructor
Point q(10,20); // calls constructor with parameters
Point* r = new Point(); // calls default constructor
Point s = p; // our default constructor not called.
. . .

Destructors
When are destructors called?

A destructor for an object is called whenever


• The scope of a local variable or parameter is exited, the destructor is
called.
• By explicitly calling the destructor.

Default constructor vs custom constructor

If you don't have anything to clean up, like memory that you allocated for
some of the members, then the default constructor is probably ok.

OOP: Copy Constructors


When copies of objects are made

A copy constructor is called whenever a new variable is created from an


object. This happens in the following cases (but not in assignment).

• A variable is declared which is initialized from another object, eg,


• Person q("Mickey"); // constructor is used to build q.
• Person r(p); // copy constructor is used to build r.
• Person p = q; // copy constructor is used to initialize
in declaration.
p = q; // Assignment operator, no constructor or
copy constructor.

• A value parameter is initialized from its corresponding argument.

f(p); // copy constructor initializes formal


value parameter.

• An object is returned by a function.

C++ calls a copy constructor to make a copy of an object in each of the


above cases. If there is no copy constructor defined for the class, C++ uses
the default copy constructor which copies each field, ie, makes a shallow
copy.

Don't write a copy constructor if shallow copies are ok

If the object has no pointers to dynamically allocated memory, a shallow


copy is probably sufficient. Therefore the default copy constructor, default
assignment operator, and default destructor are ok and you don't need to
write your own.

If you need a copy constructor, you also need a destructor and


operator=

If you need a copy constructor, it's because you need something like a deep
copy, or some other management of resources. Thus is is almost certain that
you will need a destructor and override the assignment operator.

Copy constructor syntax

The copy constructor takes a reference to a const parameter. It is const to


guarantee that the copy constructor doesn't change it, and it is a reference
because a value parameter would require making a copy, which would invoke
the copy constructor, which would make a copy of its parameter, which would
invoke the copy constructor, which ...

Here is an example of a copy constructor for the Point class, which doesn't
really need one because the default copy constructor's action of copying
fields would work fine, but it shows how it works.

//=== file Point.h =============================================


class Point {
public:
. . .
Point(const Point& p); // copy constructor
. . .
//=== file Point.cpp ==========================================
. . .
Point::Point(const Point& p) {
x = p.x;
y = p.y;
}
. . .
//=== file my_program.cpp ====================================
. . .
Point p; // calls default constructor
Point s = p; // calls copy constructor.
p = s; // assignment, not copy constructor.

Difference between copy constructor and assignment

A copy constructor is used to initialize a newly declared variable from an


existing variable. This makes a deep copy like assignment, but it is somewhat
simpler:

1. There is no need to test to see if it is being initialized from itself.


2. There is no need to clean up (eg, delete) an existing value (there is
none).
3. A reference to itself is not returned.

Unaddressed issue

[Question: When is the base (parent) class copy constructor called? Is it like
Java and the parent constructor is called at the beginning of each
constructor? Does it have to be explicit?]

Overloading Assignment
When to define assignment (and a copy constructor and
destructor)

If your object has a pointer to dynamically allocated memory, eg


allocated in the constructor, you will want to make a deep copy of the object.
Deep copies require overloading assignment, as well as defining a copy
constructor and a destructor).
Pattern

The following steps are a typical for the assignment operator.

1. No self-assignment. Test to make sure you aren't assigning an


object to itself, eg x = x. Of course no one would write that statement,
but in can happen when one side of the assignment is not so obviously
the same object. Self assignment fails because the memory associated
with the current value of the left-hand-side is deallocated before the
assignment, which would invalidate using it from the right-hand-side.
2. Delete the associated memory. Same as copy constructor.
3. Copy all the members. Same as copy constructor.
4. Return *this. This is necessary to allow multiple assignment, eg x = y
= z;

Example

//--- file Person.h


. . .
class Person {
private:
char* _name;
int _id;
public:
Person& Person::operator=(const Person& p);
. . .
}
//--- file Person.cpp
. . .
//=================================================== operator=
Person& Person::operator=(const Person& p) {
if (this != &p) { // make sure not same object
delete [] _name; // Delete old name's
memory.
_name = new char[strlen(p._name)+1]; // Get new space
strcpy(_name, p._name); // Copy new name
_id = p._id; // Copy id
}
return *this; // Return ref for multiple assignment
}//end operator=
When should your destructor be virtual?
When should your C++ object's destructor be virtual?

First of all, what does it mean to have a virtual destructor?

Well, what does it mean to have a virtual method?

If a method is virtual, then calling the method on an object always invokes the method as
implemented by the most heavily derived class. If the method is not virtual, then the
implementation corresponding to the compile-time type of the object pointer.

For example, consider this:

class Sample {
public:
void f();
virtual void vf();
};

class Derived : public Sample {


public:
void f();
void vf();
}

void function()
{
Derived d;
Sample* p = &d;
p->f();
p->vf();
}

The call to p->f() will result in a call to Sample::f because p is a pointer to a Sample.
The actual object is of type Derived, but the pointer is merely a pointer to a Sample. The
pointer type is used because f is not virtual.

On the other hand, the call to The call to p->vf() will result in a call to Derived::vf,
the most heavily derived type, because vf is virtual.

Okay, you knew that.

Virtual destructors work exactly the same way. It's just that you rarely invoke the
destructor explicitly. Rather, it's invoked when an automatic object goes out of scope or
when you delete the object.

void function()
{
Sample* p = new Derived;
delete p;
}

Since Sample does not have a virtual destructor, the delete p invokes the destructor of
the class of the pointer (Sample::~Sample()), rather than the destructor of the most
derived type (Derived::~Derived()). And as you can see, this is the wrong thing to do
in the above scenario.

Armed with this information, you can now answer the question.

A class must have a virtual destructor if it meets both of the following criteria:

• You do a delete p.
• It is possible that p actually points to a derived class.

Some people say that you need a virtual destructor if and only if you have a virtual
method. This is wrong in both directions.

Example of a case where a class has no virtual methods but still needs a virtual
destructor:

class Sample { };
class Derived : public Sample
{
CComPtr<IStream> m_p;
public:
Derived() { CreateStreamOnHGlobal(NULL, TRUE, &m_p); }
};

Sample *p = new Derived;


delete p;

The delete p will invoke Sample::~Sample instead of Derived::~Derived, resulting


in a leak of the stream m_p.

And here's an example of a case where a class has virtual methods but does not require a
virtual destructor.

class Sample { public: virtual void vf(); }


class Derived : public Sample { public: virtual void vf(); }

Derived *p = new Derived;


delete p;

Since the object deletion occurs from the pointer type that matches the type of the actual
object, the correct destructor will be invoked. This pattern happens often in COM objects,
which expose several virtual methods corresponding to its interfaces, but where the
object itself is destroyed by its own implementation and not from a base calss pointer.
(Notice that no COM interfaces contain virtual destructors.)
The problem with knowing when to make your destructor virtual or not is that you have
to know how people will be using your class. If C++ had a "sealed" keyword, then the
rule would be simpler: If you do a "delete p" where p is a pointer to an unsealed class,
then that class needs have a virtual destructor. (The imaginary "sealed" keyword makes it
explicit when a class can act as the base class for another class.)

Published Friday, May 07, 2004 7:01 AM by oldnewthing


Filed Under: Code

Comments

# re: When should your destructor be virtual?


Friday, May 07, 2004 7:50 AM by Mike G.
"Some people say that you need a virtual destructor if and only if you have a virtual
method. This is wrong in both directions."

Well, almost.

If the sizeof or layout of your class is a concern for some reason, making the destructor
virtual "costs nothing" if your base class already has a virtual method. You're already
carrying a vptr at that point.

There's rarely a reason NOT to make the destructor virtual if you already have a virtual
method, I think. (I guess it's possible you're going to create a LOT of temporary
Derived's, so the ~Derived virtual call becomes a bottleneck, but that seems very
unlikely...)

An empty virtual destructor for your last sample class would hardly be a maintenance
headache, and opens the possibility for the use case to change down the road without base
class changes.

# re: When should your destructor be virtual?


Friday, May 07, 2004 8:14 AM by Daniel
If you really don't want a virtual destructor, you should probably make the base class'
destructor protected, to prevent mistakes.

Also, there's a small mistake - Derived isn't derived in the last bit of code.

# re: When should your destructor be virtual?


Friday, May 07, 2004 8:48 AM by Raymond Chen
Fixed, thanks Daniel.

# re: When should your destructor be virtual?


Friday, May 07, 2004 8:49 AM by Raymond Chen
Mike G.: Most COM objects do not have a virtual destructor since they are destructed
from the derived class (inside the Release() methods). Yes, it doesn't cost you much (an
etra pointer in the vtable), but if your object architecture already encapsulates object
destruction in a virtual method (like COM does), then virtualizing the destructor may end
up creating confusion.

# re: When should your destructor be virtual?


Friday, May 07, 2004 8:58 AM by Marc Wallace
Are there any cases where you would *not* want to invoke the destructor of the most
derived class that has it?

In other words: somewhere, something knows that p isa Derived. Are there cases when
Derived::~Derived() is defined, but you would actually want "delete p" to do a
Simple::~Simple()?

# re: When should your destructor be virtual?


Friday, May 07, 2004 9:08 AM by Raymond Chen
I can't think of one offhand.

# Couldn't have said it better


Friday, May 07, 2004 12:08 PM by HMK's Spurious Thoughts
When should your destructor be virtual?...

# re: When should your destructor be virtual?


Friday, May 07, 2004 9:15 AM by Aarrgghh
Marc Wallace: You might want to do that if you're testing the debug heap's memory-leak
detection.

# re: When should your destructor be virtual?


Friday, May 07, 2004 9:31 AM by DrPizza
"There's rarely a reason NOT to make the destructor virtual if you already have a virtual
method, I think. (I guess it's possible you're going to create a LOT of temporary
Derived's, so the ~Derived virtual call becomes a bottleneck, but that seems very
unlikely...) "

One reason is that it needn't be necessary.

Consider for example:

struct Base
{
arbitraryType arbitraryMemberVariable;
virtual void doSomething() = 0;
~Base() {}
};
struct Derived : Base
{
arbitraryType arbitraryMemberVariable;
virtual void doSomething() { blahblahblah; }
~Derived() {}
};

// any old block for any old reason


{
const Base& b((Derived()));
}

In this case the Derived d-tor will be called in spite of being bound to a reference to Base,
because the compiler uses the static type of the temporary to figure out which destructor
to call.

Esoteric? Sure. Useless? Hell no, as anyone who's seen ScopeGuard will know.

# re: When should your destructor be virtual?


Friday, May 07, 2004 2:50 PM by Thomas Maeder
Slight inaccuracy:

The statement

The delete p will invoke Sample::~Sample instead of Derived::~Derived, resulting in a


leak of the stream m_p.

is wrong. If a delete expression is evaluated on a base class pointer that points to an


instance of a derived class, the behavior is undefined; anything can happen.

It is possible that the base class destructor is invoked and the derived clas destructor isn't,
but that's just an instance of undefined behavior. Other instances are a program crash or
the computer catching fire.

# re: When should your destructor be virtual?


Friday, May 07, 2004 3:10 PM by Raymond Chen
Ah, excellent point Thomas.

5.3.5.3: "If the static type of the operand is different from its dynamic type, the static type
shall be a base class of the operand's dynamic type and the static type shall have a virtual
destructor or the behavior is undefined."

# re: When should your destructor be virtual?


Sunday, May 09, 2004 8:27 PM by jeffdav
There you go giving away my interview questions again, Raymond.
# re: When should your destructor be virtual?
Monday, May 10, 2004 8:29 PM by Troll Buster
Don't click on the link in Gary Niger's post. It's a GNAA troll link. Like goatse.cx only a
thousand times worse.

# re: When should your destructor be virtual?


Monday, May 10, 2004 8:45 PM by Raymond Chen
Thanks, Mr. Troll Buster. I deleted the comment. It was also a clipboard stealer. Whatever
text was on your clipboard got uploaded to the site, and then you got redirected to
something unpleasant...

# re: When should your destructor be virtual?


Tuesday, May 11, 2004 3:40 AM by Florin POPA
Hi,

I think the rule about "When should your destructor be virtual? " can be:

The DTOR of base class is:


- public and MUST be virtual
- protected and then should be non-virtual

And by the way, is not a good ideea to inherit public from a class without any virtual
method.

# re: When should your destructor be virtual?


Wednesday, May 12, 2004 6:20 AM by The Other John
Wow, a clipboard stealer... never heard of that one before. Amazing the things that are
possible.

I wonder if we could perform a DNS attack on him by copying gigantic bitmaps into our
clipboard, then visiting his site :)

# re:How graphics used in VC++


Tuesday, May 18, 2004 3:06 AM by vinod
Graphics means use of graphics function
like circle(),line() etc., like Turbo c++.

# re: When should your destructor be virtual?


Friday, May 28, 2004 1:33 AM by Atul Malhotra
Yupp, it means drawing objects using graphics functions using standard graphics library
as well as using user defined classes which may or may not be inherited from the
standard classes.

# re: When should your destructor be virtual?


Friday, June 18, 2004 11:45 AM by Raymond Chen
Commenting on this article has been closed.

Q1: Tell how to check whether a linked list is circular.

A: Create two pointers, each set to the start of the list. Update each as follows:

while (pointer1) {
pointer1 = pointer1->next;
pointer2 = pointer2->next; if (pointer2) pointer2=pointer2->next;
if (pointer1 == pointer2) {
print (\"circular\n\");
}
}

Q2: OK, why does this work?

If a list is circular, at some point pointer2 will wrap around and be either at the item just
before pointer1, or the item before that. Either way, it’s either 1 or 2 jumps until they
meet.

1. What is a modifier? A modifier, also called a modifying function is a member


function that
changes the value of at least one data member. In other words, an
operation that modifies the state of an object. Modifiers are also
known as ‘mutators’. Example: The function mod is a modifier in the
following code snippet:
2. class test
3. {
4. int x,y;
5. public:
6. test()
7. {
8. x=0; y=0;
9. }
10. void mod()
11. {
12. x=10;
13. y=15;
14. }
15.};
16. What is an accessor? An accessor is a class operation that
does not modify the state of an object. The accessor functions need to
be declared as const operations
17. Differentiate between a template class and class template.
Template class: A generic definition or a parameterized class not
instantiated until the client provides the needed information. It’s
jargon for plain templates. Class template: A class template specifies
how individual classes can be constructed much like the way a class
specifies how individual objects can be constructed. It’s jargon for
plain classes.
18. When does a name clash occur? A name clash occurs
when a name is defined in more than one place. For example., two
different class libraries could give two different classes the same
name. If you try to use many class libraries at the same time, there is
a fair chance that you will be unable to compile or link the program
because of name clashes.
19. Define namespace. It is a feature in C++ to
minimize name collisions in the global name space. This namespace
keyword assigns a distinct name to a library that allows other
libraries to use the same identifier names without creating any name
collisions. Furthermore, the compiler uses the namespace signature for
differentiating the definitions.
20. What is the use of ‘using’ declaration.
A using declaration makes it possible to use a name from a namespace
without the scope operator.
21. What is an Iterator class? A class that is used to
traverse through the objects maintained by a container class. There are
five categories of iterators: input iterators, output iterators,
forward iterators, bidirectional iterators, random access. An iterator
is an entity that gives access to the contents of a container object
without violating encapsulation constraints. Access to the contents is
granted on a one-at-a-time basis in order. The order can be storage
order (as in lists and queues) or some arbitrary order (as in array
indices) or according to some ordering relation (as in an ordered
binary tree). The iterator is a construct, which provides an interface
that, when called, yields either the next element in the container, or
some value denoting the fact that there are no more elements to
examine. Iterators hide the details of access to and update of the
elements of a container class.
The simplest and safest iterators are those that permit read-only access to
the contents of a container class.
22. List out some of the OODBMS available. GEMSTONE/OPAL
of Gemstone systems, ONTOS of Ontos, Objectivity of Objectivity Inc,
Versant of Versant object technology, Object store of Object Design,
ARDENT of ARDENT software, POET of POET software.
23. List out some of the object-oriented methodologies. Object Oriented
Development (OOD) (Booch 1991,1994), Object
Oriented Analysis and Design (OOA/D) (Coad and Yourdon 1991), Object
Modelling Techniques (OMT) (Rumbaugh 1991), Object Oriented Software
Engineering (Objectory) (Jacobson 1992), Object Oriented Analysis (OOA)
(Shlaer and Mellor 1992), The Fusion Method (Coleman 1991).
24. What is an incomplete type? Incomplete types
refers to pointers in which there is non availability of the
implementation of the referenced location or it points to some location
whose value is not available for modification.
25. int *i=0x400 // i points to address 400
26. *i=0; //set the value of memory location
pointed by i.

Incomplete types are otherwise called uninitialized pointers.


27. What is a dangling pointer?
A dangling pointer arises when you use the address of an object after
its lifetime is over. This may occur in situations like returning
addresses of the automatic variables from a function or using the
address of the memory block after it is freed. The following
code snippet shows this:
28.class Sample
29.{
30.public:
31. int *ptr;
32. Sample(int i)
33. {
34. ptr = new int(i);
35. }
36.
37. ~Sample()
38. {
39. delete ptr;
40. }
41. void PrintVal()
42. {
43. cout << \"The value is \" << *ptr;
44. }
45.};
46.
47.void SomeFunc(Sample x)
48.{
49. cout << \"Say i am in someFunc \" << endl;
50.}
51.
52.int main()
53.{
54. Sample s1 = 10;
55. SomeFunc(s1);
56. s1.PrintVal();
57.}

In the above example when PrintVal() function is


called it is called by the pointer that has been freed by the
destructor in SomeFunc.

58. Differentiate between the message and method.


Message:
o Objects communicate by sending messages to each other.
o A message is sent to invoke a method.

Method

o Provides response to a message.


o It is an implementation of an operation.
59. What is an adaptor class or Wrapper class?
A class that has no functionality of its own. Its member functions hide
the use of a third party software component or an object with the
non-compatible interface or a non-object-oriented implementation.
60. What is a Null object? It is an object of some
class whose purpose is to indicate that a real object of that class
does not exist. One common use for a null object is a return value from
a member function that is supposed to return an object with some
specified properties but cannot find such an object.
61. What is class invariant? A class invariant is a
condition that defines all valid states for an object. It is a logical
condition to ensure the correct working of a class. Class invariants
must hold when an object is created, and they must be preserved under
all operations of the class. In particular all class invariants are
both preconditions and post-conditions for all operations or member
functions of the class.
62. What do you mean by Stack unwinding? It is a
process during exception handling when the destructor is called for all
local objects between the place where the exception was thrown and
where it is caught.
63. Define precondition and post-condition to a member function.
Precondition: A precondition is a condition that must be true on entry
to a member function. A class is used correctly if preconditions are
never false. An operation is not responsible for doing anything
sensible if its precondition fails to hold. For example, the interface
invariants of stack class say nothing about pushing yet another element
on a stack that is already full. We say that isful() is a precondition
of the push operation. Post-condition: A post-condition is a condition
that must be true on exit from a member function if the precondition
was valid on entry to that function. A class is implemented correctly
if post-conditions are never false. For example, after pushing an
element on the stack, we know that isempty() must necessarily hold.
This is a post-condition of the push operation.
64. What are the conditions that have to be met for a condition to be an
invariant of the class?
o The condition should hold at the end of every constructor.
o The condition should hold at the end of every mutator (non-const)
operation.
65. What are proxy objects? Objects that stand for other objects are called
proxy objects or surrogates.
66.template <class t="">
67.class Array2D
68.{
69. public:
70. class Array1D
71. {
72. public:
73. T& operator[] (int index);
74. const T& operator[] (int index)const;
75. };
76.
77. Array1D operator[] (int index);
78. const Array1D operator[] (int index) const;
79.};
The following then becomes legal:

Array2D<float>data(10,20);
cout<<data[3][6]; // fine

Here data[3] yields an Array1D object


and the operator [] invocation on that object yields the float in
position(3,6) of the original two dimensional array. Clients of the
Array2D class need not be aware of the presence of the Array1D class.
Objects of this latter class stand for one-dimensional array objects
that, conceptually, do not exist for clients of Array2D. Such clients
program as if they were using real, live, two-dimensional arrays. Each
Array1D object stands for a one-dimensional array that is absent from a
conceptual model used by the clients of Array2D. In the above example,
Array1D is a proxy class. Its instances stand for one-dimensional
arrays that, conceptually, do not exist.

80. Name some pure object oriented languages. Smalltalk, Java, Eiffel,
Sather.
81. Name the operators that cannot be overloaded. sizeof, ., .*, .->, ::, ?:
Salam in the comments notes that -> can be overloaded.
82. What is a node class? A node class is a class that,
o relies on the base class for services and implementation,
o provides a wider interface to the users than its base class,
o relies primarily on virtual functions in its public interface
o depends on all its direct and indirect base class
o can be understood only in the context of the base class
o can be used as base for further derivation
o 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.

83. What is an orthogonal base class?


If two base classes have no overlapping methods or data they are said
to be independent of, or orthogonal to each other. Orthogonal in the
sense means that two classes operate in different dimensions and do not
interfere with each other in any way. The same derived class may
inherit such classes with no difficulty.
84. What is a container class? What are the types of container classes?

A container class is a class that is used to hold objects in memory or


external storage. A container class acts as a generic holder. A
container class has a predefined behavior and a well-known interface. A
container class is a supporting class whose purpose is to hide the
topology used for maintaining the list of objects in memory. When a
container class contains a group of mixed objects, the container is
called a heterogeneous container; when the container is holding a group
of objects that are all the same, the container is called a homogeneous
container.

85. how to make a function which can take any no of argument?what is va_list.

va_arg, va_end, va_start


Access variable-argument lists.

type va_arg( va_list arg_ptr, type );

void va_end( va_list arg_ptr );

void va_start( va_list arg_ptr ); (UNIX version)

void va_start( va_list arg_ptr, prev_param ); (ANSI version)

Routine Required Header Optional Headers Compatibility


va_arg <stdio.h> and <varargs.h>1 ANSI, Win 95, Win NT
<stdarg.h>
va_end <stdio.h> and <varargs.h>1 ANSI, Win 95, Win NT
<stdarg.h>
va_start <stdio.h> and <varargs.h>1 ANSI, Win 95, Win NT
<stdarg.h>

1
Required for UNIX V compatibility.

For additional compatibility information, see Compatibility in the Introduction.

Libraries

LIBC.LIB Single thread static library, retail version


LIBCMT.LIB Multithread static library, retail version
MSVCRT.LIB Import library for MSVCRT.DLL, retail version

Return Value

va_arg returns the current argument; va_start and va_end do not return values.

Parameters
type

Type of argument to be retrieved

arg_ptr

Pointer to list of arguments

prev_param

Parameter preceding first optional argument (ANSI only)

Remarks

The va_arg, va_end, and va_start macros provide a portable way to access the
arguments to a function when the function takes a variable number of arguments.
Two versions of the macros are available: The macros defined in STDARG.H conform
to the ANSI C standard, and the macros defined in VARARGS.H are compatible with
the UNIX System V definition. The macros are:

va_alist

Name of parameter to called function (UNIX version only)

va_arg

Macro to retrieve current argument

va_dcl

Declaration of va_alist (UNIX version only)

va_end

Macro to reset arg_ptr

va_list

typedef for pointer to list of arguments defined in STDIO.H

va_start

Macro to set arg_ptr to beginning of list of optional arguments (UNIX version only)

Both versions of the macros assume that the function takes a fixed number of
required arguments, followed by a variable number of optional arguments. The
required arguments are declared as ordinary parameters to the function and can be
accessed through the parameter names. The optional arguments are accessed
through the macros in STDARG.H or VARARGS.H, which set a pointer to the first
optional argument in the argument list, retrieve arguments from the list, and reset
the pointer when argument processing is completed.

The ANSI C standard macros, defined in STDARG.H, are used as follows:

• All required arguments to the function are declared as parameters in the


usual way. va_dcl is not used with the STDARG.H macros.

• va_start sets arg_ptr to the first optional argument in the list of arguments
passed to the function. The argument arg_ptr must have va_list type. The
argument prev_param is the name of the required parameter immediately
preceding the first optional argument in the argument list. If prev_param is
declared with the register storage class, the macro’s behavior is undefined.
va_start must be used before va_arg is used for the first time.

• va_arg retrieves a value of type from the location given by arg_ptr and
increments arg_ptr to point to the next argument in the list, using the size of
type to determine where the next argument starts. va_arg can be used any
number of times within the function to retrieve arguments from the list.

• After all arguments have been retrieved, va_end resets the pointer to NULL.

The UNIX System V macros, defined in VARARGS.H, operate somewhat differently:

• Any required arguments to the function can be declared as parameters in the


usual way.

• The last (or only) parameter to the function represents the list of optional
arguments. This parameter must be named va_alist (not to be confused with
va_list, which is defined as the type of va_alist).

• va_dcl appears after the function definition and before the opening left brace
of the function. This macro is defined as a complete declaration of the
va_alist parameter, including the terminating semicolon; therefore, no
semicolon should follow va_dcl.

• Within the function, va_start sets arg_ptr to the beginning of the list of
optional arguments passed to the function. va_start must be used before
va_arg is used for the first time. The argument arg_ptr must have va_list
type.

• va_arg retrieves a value of type from the location given by arg_ptr and
increments arg_ptr to point to the next argument in the list, using the size of
type to determine where the next argument starts. va_arg can be used any
number of times within the function to retrieve the arguments from the list.

• After all arguments have been retrieved, va_end resets the pointer to NULL.

Example

/* VA.C: The program below illustrates passing a variable


* number of arguments using the following macros:
* va_start va_arg va_end
* va_list va_dcl (UNIX only)
*/

#include <stdio.h>
#define ANSI /* Comment out for UNIX version */
#ifdef ANSI /* ANSI compatible version */
#include <stdarg.h>
int average( int first, ... );
#else /* UNIX compatible version */
#include <varargs.h>
int average( va_list );
#endif

void main( void )


{
/* Call with 3 integers (-1 is used as terminator). */
printf( "Average is: %d\n", average( 2, 3, 4, -1 ) );

/* Call with 4 integers. */


printf( "Average is: %d\n", average( 5, 7, 9, 11, -1 ) );

/* Call with just -1 terminator. */


printf( "Average is: %d\n", average( -1 ) );
}

/* Returns the average of a variable list of integers. */


#ifdef ANSI /* ANSI compatible version */
int average( int first, ... )
{
int count = 0, sum = 0, i = first;
va_list marker;

va_start( marker, first ); /* Initialize variable arguments. */


while( i != -1 )
{
sum += i;
count++;
i = va_arg( marker, int);
}
va_end( marker ); /* Reset variable arguments. */
return( sum ? (sum / count) : 0 );
}
#else /* UNIX compatible version must use old-style definition.
*/
int average( va_alist )
va_dcl
{
int i, count, sum;
va_list marker;

va_start( marker ); /* Initialize variable arguments. */


for( sum = count = 0; (i = va_arg( marker, int)) != -1; count++ )
sum += i;
va_end( marker ); /* Reset variable arguments. */
return( sum ? (sum / count) : 0 );
}
#endif

Output

Average is: 3
Average is: 8
Average is: 0
/* This following program defines and demonstrates the function
"_outtextf": */
/* Compile options needed: none
*/

#include <stdio.h>
#include <graph.h>
#include <stdarg.h>

int _outtextf (char *format,...);


void main (void);

void main (void)


{ /* Clear the screen and display "Hello, world #87!" */
_clearscreen (_GCLEARSCREEN);
_outtextf ("Hello, %s #%d!","world",87);
}

int _outtextf (char *format,...)


{ va_list arglist;
char buffer[150]; /*Must be large enough to hold formatted string*/
int retval;

va_start (arglist,format);
retval = vsprintf(buffer,format,arglist);
va_end (arglist);

_outtext (buffer);
return (retval);
}
//Using CString::FormatV(), you can write functions like the following:

void WriteLogEntry(CStdioFile& refFile, LPCTSTR pstrFormat, ...)


{
CTime timeWrite;
timeWrite = CTime::GetCurrentTime();

// write the time out


CString str = timeWrite.Format("%d %b %y %H:%M:%S - ");
refFile.Write(str, str.GetLength());

// format and write the data we were given


va_list args;
va_start(args, pstrFormat);
str.FormatV(pstrFormat, args);
refFile.Write(str, str.GetLength());
// put a newline
refFile.Write("\n", 1);
return;
}

You can call the above function with any number of parameters, for example:

WriteLogEntry(fileLog, "Program started");


WriteLogEntry(fileLog, "Processed %d bytes", 91341);
WriteLogEntry(fileLog, "%d error(s) found in %d line(s)", 10, 1351);
WriteLogEntry(fileLog, "Program completed");

which would add output to your fileLog file similar to the following:

17 Apr 97 12:34:53 - Program started


17 Apr 97 12:34:59 - Processed 91341 bytes
17 Apr 97 12:35:22 - 10 error(s) found in 1351 line(s)
17 Apr 97 12:35:23 - Program completed

1. What is IUnknown? What methods are provided by IUnknown? It is a


generally good idea to have an answer for this question if you claim you know
COM in your resume. Otherwise, you may consider your interview failed at
this point. IUnknown is the base interface of COM. All other interfaces must
derive directly or indirectly from IUnknown. There are three methods in that
interface: AddRef, Release and QueryInterface.
2. What are the purposes of AddRef, Release and QueryInterface
functions? AddRef increments reference count of the object, Release
decrements reference counter of the object and QueryInterface obtains a
pointer to the requested interface.
3. What should QueryInterface functions do if requested object was not
found? Return E_NOINTERFACE and nullify its out parameter.
4. How can would you create an instance of the object in COM? Well, it all
depends on your project. Start your answer from CoCreateInstance or
CoCreateInstanceEx, explain the difference between them. If interviewer is
still not satisfied, you’ll have to explain the whole kitchen behind the scenes,
including a difference between local server and inproc server, meaning and
mechanism of class factory, etc. You may also mention other methods of
object creation like CoGetInstanceFromFile, but discussion will likely turn to
discussion of monikers then.
5. What happens when client calls CoCreateInstance? Again, all depends
on the level of detail and expertise of interviewer. Start with simple
explanation of class object and class factory mechanism. Further details would
depend on a specific situation.
6. What the limitations of CoCreateInstance? Well, the major problems with
CoCreateInstance is that it is only able to create one object and only on local
system. To create a remote object or to get several objects, based on single
CLSID, at the same time, one should use CoCreateInstanceEx.
7. What is aggregation? How can we get an interface of the aggregated
object? Aggregation is the reuse mechanism, in which the outer object
exposes interfaces from the inner object as if they were implemented on the
outer object itself. This is useful when the outer object would always delegate
every call to one of its interfaces to the same interface in the inner object.
Aggregation is actually a specialized case of containment/delegation, and is
available as a convenience to avoid extra implementation overhead in the
outer object in these cases. We can get a pointer to the inner interface,
calling QueryInterface of the outer object with IID of the inner interface.
8. C is aggregated by B, which in turn aggregated by A. Our client
requested C. What will happen? QueryInterface to A will delegate request
to B which, in turn, will delegate request for the interface to C. This pointer
will be returned to the client.
9. What is a moniker ? An object that implements the IMoniker interface. A
moniker acts as a name that uniquely identifies a COM object. In the same
way that a path identifies a file in the file system, a moniker identifies a COM
object in the directory namespace.
10. What’s the difference, if any, between OLE and COM? OLE is build on
top of COM. The question is not strict, because OLE was built over COM for
years, while COM as a technology was presented by Microsoft a few years
ago. You may mention also that COM is a specification, while OLE is a
particular implementation of this specification, which in today’s world is not
exactly true as well, because what people call COM today is likely
implementation of COM spec by Microsoft.
11. What’s the difference between COM and DCOM? Again, the question
does not require strict answer. Any DCOM object is yet a COM object (DCOM
extends COM) and any COM object may participate in DCOM transactions.
DCOM introduced several improvements/optimizations for distributed
environment, such as MULTI_QI (multiple QueryInterface()), security contexts
etc. DCOM demonstrated importance of surrogate process (you cannot run in-
proc server on a remote machine. You need a surrogate process to do that.)
DCOM introduced a load balancing.
12. What is a dual interface? Dual interface is one that supports both -
IDispatch interface and vtbl-based interface. Therefore, it might be used in
scripting environment like VBScript and yet to use power and speed of vtbl-
based interface for non-scripting environment. Discussion then may easily
transform into analyzing of dual interface problems - be prepared to this
twist.
13. Can you have two dual interfaces in one class? Yes. You may have two
dual interfaces in one class, but only one of them may be default. The bottom
line is that you cannot work with two dual interfaces at the same time due to
nature of dual interface! To support two dual interfaces in VB you would write
something like:
14. dim d1 as IDualInterface1
15. dim d2 as IDualInterface2
16. set d1 = new MyClassWithTwoDuals
17. set d2 = d1

In ATL’s class you would have to use macro


COM_INTERFACE_ENTRY2(IDispatch,
IDualInterface1), to distinguish between different dual interfaces.

18. What is marshalling by value? Some objects can essentially be considered


static: regardless of which methods are called, the state of the object does
not change. Instead of accessing such an object remotely, it is possible to
copy the static state of the object and create a new object with the same
state information on the caller side. The caller won’t be able to notice the
difference, but calls will be more efficient because they do not involve network
round trips. This is called “marshaling by value”.
19. What is a multi-threaded apartment (MTA)? Single-threaded
apartment (STA)? This is pretty difficult question to describe shortly.
Anyway, apartments were introduced by Microsoft in NT 3.51 and late
Windows 95 to isolate the problem of running legacy non-thread safe code
into multithreaded environment. Each thread was “encapsulated” into so
called single-threaded apartment. The reason to create an object in
apartment is thread-safety. COM is responsible synchronize access to the
object even if the object inside of the apartment is not thread-safe.
Multithreaded apartments (MTA, or free threading apartment) were
introduced in NT 4.0. Idea behind MTA is that COM is not responsible to
synchronize object calls between threads. In MTA the developer is responsible
for that. See “Professional DCOM Programming” of Dr. Grimes et al. or
“Essential COM” of Don Box for the further discussion on this topic.
20. Let’s assume we have object B and aggregated object C (in-proc
server), created by B. Can you access any interface of B from C?
What’s the difference between aggregated and contained objects?
Yes, you can. This is fundamental postulate of COM: “If you can get there
from here, you can get there from anywhere”, i.e. QI’ing for IUnknown you
may proceed and to get a pointer to any other interface, supported by the
object. Aggregated object exposes its interface directly, without visible
intervention of the object container. Contained object is created within the
object container and its interfaces might be altered or filtered by the object
container.
21. What is ROT ? GIT ? Count pros and cons of both. By definition, running
object table (ROT) is a globally accessible table on each computer that keeps
track of all COM objects in the running state that can be identified by a
moniker. Moniker providers register an object in the table, which increments
the object’s reference count. Before the object can be destroyed, its moniker
must be released from the table. Global Interface Table (GIT) allows any
apartment (either single- or multi-threaded) in a process to get access to
an interface implemented on an object in any other apartment in the
process.
22. If you have an object with two interfaces, can you custom marshal
one of them? No! The decision to use custom marshaling is an all-or-nothing
decision; an object has to custom marshal all its interfaces or none of them.
23. Is there a way to register in-proc server without regsvr32.exe? Yes.
Call DllRegisterServer() from the client. Do not forget to call
DLLUnregisterServer() from the same client. You may also use Registrar
object for the same purpose or use direct manipulation of the windows
registry.
24. What is VARIANT? Why and where would you use it? VARIANT is a huge
union containing automation type. This allows easy conversion of one
automation type to another. The biggest disadvantage of VARIANT is size of
the union.
25. How can you guarantee that only remote server is ever created by a
client? Create an object (call CoCreateObjectEx()) with
CLSCTX_REMOTE_SERVER flag.
26. What is __declspec(novtable)? Why would you need this?
__declspec(novtable) is a Microsoft’s compiler optimization. The main idea of
this optimization is to strip the vtable initialization code from abstract class
(for abstract class the vtable is empty, while it is initialized in contructor)
27. What is an IDL? IDL stands for Interface Definition Language. IDL is the
language to describe COM interfaces.
28. What is In-proc? In-proc is in-process COM object, i.e. COM object that
implemented as DLL and supposed to be hosted by a container. When you
have to instantiate the in-proc object remotely, you may use DLLHost.exe
application that was design specially for this purpose.
29. What is OLE? OLE is an object and embedding first implementation of COM
spec available from MS before COM was officially named COM.
30. Give examples of OLE usage. The most famous examples are probably
drag and drop and structured storage implementations.
31. What are 2 storage types for composite document? Storage and
Stream.
32. Is .doc document a compound document? Is it a structured storage?
Compound document is a document that contains information about other
documents hosted in this document. All office documents _may_ be
compound documents, but may be not. Word documents from version 6.0 and
up are stored as structured storage.

Q1: Tell how to check whether a linked list is circular.

A: Create two pointers, each set to the start of the list. Update each as follows:

while (pointer1) {
pointer1 = pointer1->next;
pointer2 = pointer2->next; if (pointer2) pointer2=pointer2->next;
if (pointer1 == pointer2) {
print (\"circular\n\");
}
}

Q2: OK, why does this work?

If a list is circular, at some point pointer2 will wrap around and be either at the item just
before pointer1, or the item before that. Either way, it’s either 1 or 2 jumps until they
meet.

1. What is a modifier? A modifier, also called a modifying function is a member


function that
changes the value of at least one data member. In other words, an
operation that modifies the state of an object. Modifiers are also
known as ‘mutators’. Example: The function mod is a modifier in the
following code snippet:
2. class test
3. {
4. int x,y;
5. public:
6. test()
7. {
8. x=0; y=0;
9. }
10. void mod()
11. {
12. x=10;
13. y=15;
14. }
15.};
16. What is an accessor? An accessor is a class operation that
does not modify the state of an object. The accessor functions need to
be declared as const operations
17. Differentiate between a template class and class template.
Template class: A generic definition or a parameterized class not
instantiated until the client provides the needed information. It’s
jargon for plain templates. Class template: A class template specifies
how individual classes can be constructed much like the way a class
specifies how individual objects can be constructed. It’s jargon for
plain classes.
18. When does a name clash occur? A name clash occurs
when a name is defined in more than one place. For example., two
different class libraries could give two different classes the same
name. If you try to use many class libraries at the same time, there is
a fair chance that you will be unable to compile or link the program
because of name clashes.
19. Define namespace. It is a feature in C++ to
minimize name collisions in the global name space. This namespace
keyword assigns a distinct name to a library that allows other
libraries to use the same identifier names without creating any name
collisions. Furthermore, the compiler uses the namespace signature for
differentiating the definitions.
20. What is the use of ‘using’ declaration.
A using declaration makes it possible to use a name from a namespace
without the scope operator.
21. What is an Iterator class? A class that is used to
traverse through the objects maintained by a container class. There are
five categories of iterators: input iterators, output iterators,
forward iterators, bidirectional iterators, random access. An iterator
is an entity that gives access to the contents of a container object
without violating encapsulation constraints. Access to the contents is
granted on a one-at-a-time basis in order. The order can be storage
order (as in lists and queues) or some arbitrary order (as in array
indices) or according to some ordering relation (as in an ordered
binary tree). The iterator is a construct, which provides an interface
that, when called, yields either the next element in the container, or
some value denoting the fact that there are no more elements to
examine. Iterators hide the details of access to and update of the
elements of a container class.
The simplest and safest iterators are those that permit read-only access to
the contents of a container class.
22. List out some of the OODBMS available. GEMSTONE/OPAL
of Gemstone systems, ONTOS of Ontos, Objectivity of Objectivity Inc,
Versant of Versant object technology, Object store of Object Design,
ARDENT of ARDENT software, POET of POET software.
23. List out some of the object-oriented methodologies. Object Oriented
Development (OOD) (Booch 1991,1994), Object
Oriented Analysis and Design (OOA/D) (Coad and Yourdon 1991), Object
Modelling Techniques (OMT) (Rumbaugh 1991), Object Oriented Software
Engineering (Objectory) (Jacobson 1992), Object Oriented Analysis (OOA)
(Shlaer and Mellor 1992), The Fusion Method (Coleman 1991).
24. What is an incomplete type? Incomplete types
refers to pointers in which there is non availability of the
implementation of the referenced location or it points to some location
whose value is not available for modification.
25. int *i=0x400 // i points to address 400
26. *i=0; //set the value of memory location
pointed by i.

Incomplete types are otherwise called uninitialized pointers.

27. What is a dangling pointer?


A dangling pointer arises when you use the address of an object after
its lifetime is over. This may occur in situations like returning
addresses of the automatic variables from a function or using the
address of the memory block after it is freed. The following
code snippet shows this:
28.class Sample
29.{
30.public:
31. int *ptr;
32. Sample(int i)
33. {
34. ptr = new int(i);
35. }
36.
37. ~Sample()
38. {
39. delete ptr;
40. }
41. void PrintVal()
42. {
43. cout << \"The value is \" << *ptr;
44. }
45.};
46.
47.void SomeFunc(Sample x)
48.{
49. cout << \"Say i am in someFunc \" << endl;
50.}
51.
52.int main()
53.{
54. Sample s1 = 10;
55. SomeFunc(s1);
56. s1.PrintVal();
57.}

In the above example when PrintVal() function is


called it is called by the pointer that has been freed by the
destructor in SomeFunc.

58. Differentiate between the message and method.


Message:
o Objects communicate by sending messages to each other.
o A message is sent to invoke a method.

Method

o Provides response to a message.


o It is an implementation of an operation.
59. What is an adaptor class or Wrapper class?
A class that has no functionality of its own. Its member functions hide
the use of a third party software component or an object with the
non-compatible interface or a non-object-oriented implementation.
60. What is a Null object? It is an object of some
class whose purpose is to indicate that a real object of that class
does not exist. One common use for a null object is a return value from
a member function that is supposed to return an object with some
specified properties but cannot find such an object.
61. What is class invariant? A class invariant is a
condition that defines all valid states for an object. It is a logical
condition to ensure the correct working of a class. Class invariants
must hold when an object is created, and they must be preserved under
all operations of the class. In particular all class invariants are
both preconditions and post-conditions for all operations or member
functions of the class.
62. What do you mean by Stack unwinding? It is a
process during exception handling when the destructor is called for all
local objects between the place where the exception was thrown and
where it is caught.
63. Define precondition and post-condition to a member function.
Precondition: A precondition is a condition that must be true on entry
to a member function. A class is used correctly if preconditions are
never false. An operation is not responsible for doing anything
sensible if its precondition fails to hold. For example, the interface
invariants of stack class say nothing about pushing yet another element
on a stack that is already full. We say that isful() is a precondition
of the push operation. Post-condition: A post-condition is a condition
that must be true on exit from a member function if the precondition
was valid on entry to that function. A class is implemented correctly
if post-conditions are never false. For example, after pushing an
element on the stack, we know that isempty() must necessarily hold.
This is a post-condition of the push operation.
64. What are the conditions that have to be met for a condition to be an
invariant of the class?
o The condition should hold at the end of every constructor.
o The condition should hold at the end of every mutator (non-const)
operation.
65. What are proxy objects? Objects that stand for other objects are called
proxy objects or surrogates.
66.template <class t="">
67.class Array2D
68.{
69. public:
70. class Array1D
71. {
72. public:
73. T& operator[] (int index);
74. const T& operator[] (int index)const;
75. };
76.
77. Array1D operator[] (int index);
78. const Array1D operator[] (int index) const;
79.};

The following then becomes legal:

Array2D<float>data(10,20);
cout<<data[3][6]; // fine

Here data[3] yields an Array1D object


and the operator [] invocation on that object yields the float in
position(3,6) of the original two dimensional array. Clients of the
Array2D class need not be aware of the presence of the Array1D class.
Objects of this latter class stand for one-dimensional array objects
that, conceptually, do not exist for clients of Array2D. Such clients
program as if they were using real, live, two-dimensional arrays. Each
Array1D object stands for a one-dimensional array that is absent from a
conceptual model used by the clients of Array2D. In the above example,
Array1D is a proxy class. Its instances stand for one-dimensional
arrays that, conceptually, do not exist.

80. Name some pure object oriented languages. Smalltalk, Java, Eiffel,
Sather.
81. Name the operators that cannot be overloaded. sizeof, ., .*, .->, ::, ?:
Salam in the comments notes that -> can be overloaded.
82. What is a node class? A node class is a class that,
o relies on the base class for services and implementation,
o provides a wider interface to the users than its base class,
o relies primarily on virtual functions in its public interface
o depends on all its direct and indirect base class
o can be understood only in the context of the base class
o can be used as base for further derivation
o 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.

83. What is an orthogonal base class?


If two base classes have no overlapping methods or data they are said
to be independent of, or orthogonal to each other. Orthogonal in the
sense means that two classes operate in different dimensions and do not
interfere with each other in any way. The same derived class may
inherit such classes with no difficulty.
84. What is a container class? What are the types of container classes?

A container class is a class that is used to hold objects in memory or


external storage. A container class acts as a generic holder. A
container class has a predefined behavior and a well-known interface. A
container class is a supporting class whose purpose is to hide the
topology used for maintaining the list of objects in memory. When a
container class contains a group of mixed objects, the container is
called a heterogeneous container; when the container is holding a group
of objects that are all the same, the container is called a homogeneous
container.

Você também pode gostar