Oracle dba Interview Questions

Oracle dba Interview Questions


1. What Is Oracle Database?

Oracle Database is a relational database management system (RDBMS) which is used to store and retrieve the large amounts of data. Oracle Database had physical and logical structures. Logical structures and physical structures are separated from each other

2. Explain Oracle Grid Architecture?

Grid computing is a information technology architecture that provides lower cost enterprise information systems. Using grid computing, independent hardware, and software components can be connected and rejoined on demand to meet the changing needs of businesses. It also enables the use of smaller individual hardware components.

3. What Is The Difference Between Large Dedicated Server And Oracle Grid?

Large dedicated server

It has expensive costly components.

High incremental costs.

It has single point of failure.

Enterprise service at higher cost.

Oracle Grid

It has low cost modular components.

Low incremental costs.

It has no single point of failure.

Enterprise service at low cost.

4. What Are The Computing Components Of Oracle Grid?

The computing componenets of oracle grid are

Oracle Enterprise Manager and Grid Control

Oracle 10g Database and Real Application Clusters.

ASM Storage Grid.

5. What Is Server Virtualization?

Oracle Real Application Clusters 10g (RAC) enables a single database to run across multiple clustered nodes in a grid, pooling the processing resources of several standard machines.

6. What Is Storage Virtualization?

The Oracle Automatic Storage Management (ASM) is a feature of Oracle Database 10g which provides a virtual layer between the database and storage so that group of disks can be treated as a single disk group and disks can be dynamically added or removed while keeping databases online.

7. What Is Grid Management Feature?

The Grid Management feature of Oracle Enterprise Manager 10g provides a single console to manage multiple systems together as a logical group.

8. When Oracle Allocates An Sga?

When Oracle starts, it reads the initialization parameter file to determine the values of initialization parameters. After this, it allocates an SGA and creates background processes.

9. What Is An Oracle Instance?

When you start, the database instance comes into picture into system memory. Combination of the SGA and the Oracle processes is called an Oracle instance.

10. What Are The Several Tools For Interacting With The Oracle Database Using Sql?

There are several tools for interfacing with the database using SQL

Oracle SQL*Plus and iSQL*Plus

Oracle Forms, Reports, and Discoverer

Oracle Enterprise Manager

Third-party tools



11. How Oracle Works?

An instance has started on the database server.

A client established a connection to the server, using the proper Oracle Net Services driver.

The server creates a dedicated server process on behalf of the user process.

The user executes SQL statement and commits the transaction.

The server process receives the statement and checks for any shared SQL area that contains a similar SQL.

The server process retrieves data from datafile (table) or SGA.

The server process modifies data in the SGA area. The DBWn process writes modified blocks permanently to disk. The LGWR process records the transaction in the redo log file.

The server process sends a message to the application.

12. What Contains Oracle Physical Database Structure?

It contains


Control Files

Redo Log Files

Archive Log Files

Parameter Files

Alert and Trace Log Files

Backup Files

13. What Is A Tablespace

Oracle use Tablespace for logical data Storage. Physically, data will get stored in Datafiles. Datafiles will be connected to tablespace. A tablespace can have multiple datafiles. A tablespace can have objects from different schema's and a schema can have multiple tablespace's. Database creates "SYSTEM tablespace" by default during database creation. It contains read only data dictionary tables which contains the information about the database.

14. What Is A Control File?

Control file is a binary file which stores Database name, associated data files, redo files, DB creation time and current log sequence number. Without control file database cannot be started and can hamper data recovery.

15. What Are Data Blocks?

Oracle stores data in data blocks also called as logical blocks, Oracle blocks or pages. A data block represents specific number of bytes of space on disk.

16. What Is An Extent?

An extent is a specific number of consecutive data blocks allocated for storing a specific type of information.

17. What Is A Segment?

A segment is a group of extents, each of which has been allocated for a specific data structure and all of which are stored in the same table-space.

18. What Is Rollback Segment ?

Database contain one or more Rollback Segments to roll back transactions and data recovery.

19. What Are The Different Type Of Segments ?

Data Segment(for storing User Data), Index Segment (for storing index), Rollback Segment and Temporary Segment.

20. What Is An Oracle Schema?

A user account and its associated data including tables, views, indexes, clusters, sequences,procedures, functions, triggers,packages and database links is known as Oracle schema. System, SCOTT etc are default schema's. We can create a new Schema/User. But we can't drop default database schema's.

21. When And How Oracle Database Creates A Schema?

Oracle Database automatically creates a schema when you create a user.

22. What Is A View?

A view is a tailored presentation of the data contained in one or more tables or other views. A view is output of a query and treats it as a table. Therefore, a view can be thought of as a stored query or a virtual table. A view is not assigned any storage space, nor does a view actually contain data.

23. How Views Are Used?

It provides security by restricting access to a predetermined set of rows or columns of a table. It hides data complexity. It simplifies statements for the user.

An example would be the views, which allow users to select data from multiple tables without actually knowing how to perform a join.

It presents the data in a different perspective from that of the base table. It isolate applications from changes in definitions of base tables. It saves complex queries.

24. What Are Materialized Views?

These are schema objects that are used to summarize, compute, replicate, and distribute data. They can be used in various environments for computation such as data warehousing, decision support, and distributed or mobile computing and it also provides local access to data rather than accessing from remote sites. In data warehouses, MVs are used to compute and store aggregated data.

25. What Is A Dimension?

A dimension is hierarchical relationships between pairs of columns or column sets. Each value at the child level is tied with one value at the parent level. A dimension is a container of logical relationships between columns and it does not contain any data.

26. Explain Sequence Generator In Oracle?

The sequence generator gives a sequential series of numbers.The sequence generator is especially useful for generating unique sequential numbers. Sequence numbers are Oracle integers of up to 38 digits defined in the database. A sequence definition provides information, such as

The sequence name

ascending or descending sequence

The interval between numbers

Whether Oracle should cache sequence numbers in memory

Sequence numbers are generated independent of any tables. The same sequence generator can be used for many tables. Sequence number generation can be used to produce primary keys for your data automatically. Oracle stores the definitions of all sequences for a particular database as rows in data dictionary table in the SYSTEM table- space.

27. What Is An Index?

Indexes are structures associated with tables and clusters. You can create indexes on one or more columns of a table to enhance the speed of SQL statement execution on that table. Just as the index in Oracle manual helps you to locate information faster than if there were no indexes. An Oracle index provides a faster access path to table data.

28. List Out Indexing Scheme That Oracle Provides?

Oracle provides several indexing schemes

B-tree indexes

B-tree cluster indexes

Hash cluster indexes

Reverse key indexes

Bitmap indexes

Bitmap join indexes

29. What Is A Synonyms?

A synonym is an alias for database objects such as table, view, materialized view, sequence, procedure, function, package. Because a synonym is simply an alias, it does not require storage other than its data dictionary definition.

30. Give An Example Of Synonyms?

CREATE PUBLIC SYNONYM sales FOR jward.sales_data;

After the public synonym is created, you can query the table SALES_DATA with a simple SQL statement

SELECT * FROM sales;

31. What Is Concurrency In Oracle?

The multiuser database management system's concern is how to control concurrency, which is the concurrent access of the same data by multiple users. Without sufficient concurrency controls, data could be updated or changed improperly, trading off with data integrity. To manage data concurrency is to make each user wait for a turn.

The goal of a database management system is to decrease the waiting time so it is either nonexistent or negligible to each user. The data manipulation language statements should proceed with as little intervention as possible, and destructive interactions among concurrent transactions should be prevented.

Destructive interaction is any interaction that updates data or alters underlying data structures incorrectly. Neither performance nor data integrity can be sacrificed. Oracle solves such problems by using various types of locks and a multi-version consistency model.

32. Explain Briefly Shared Server Architecture?

This architecture removes the need for a dedicated server process for each connection. A dispatcher routes various incoming network session requests to a shared server processes pool. An idle shared server process from a shared pool of server processes chooses a request from a common queue, which means a small number of shared servers can do the same amount of processing as many dedicated servers.

It is because of the amount of memory required for each user is comparatively small, less memory and process management are required, and more users can be supported.

33. What Are Archiver Processes?

It copies redo log files to a designated storage device after a log switch has occurred. Archiver processes are there only when the database is in ARCHIVELOG mode, and automatic archiving is enabled. An Oracle instance can have up to 10 Archi ver processes (ARC0 to ARC9). The LGWR process starts a new ARCn process whenever the current number of Archiver processes is insufficient to handle the workload.

34. What Are Job Queue Processes?

Job queue processes are used for processing batch. They run user jobs. They can be viewed as a scheduler service that can be used to schedule jobs like PL/SQL statements or procedures on an Oracle instance.




35. What Is Recoverer Process?

The re-coverer process (RECO) is a background process used with the distributed database configuration that automatically resolves failures. The RECO process of a node automatically connects to other databases involved in an in- doubt distributed transaction.

36. What Is Process Monitor Process?

It performs process recovery when a user process fails. Process Monitor is responsible for cleaning up the database buffer cache and reclaiming resources that the user process was using. Process Monitor also registers information about the instance and dispatcher processes with the network listener.

37. What Is System Monitor Process?

It performs recovery, if necessary, at instance startup.

If any terminated transactions were skipped during instance recovery due to file-read or offline errors, System Monitor Process recovers them when the tablespace or file is brought back online.

With Application Clusters, the System Monitor process of one instance can perform instance recovery for a failed CPU or instance.

38. What Is Log Writer Process?


It is responsible for writing the redo log buffer to a redo log file on disk. Log Writer writes all redo entries which is copied into the buffer since the last time it wrote.

When a user issues a commit statement, Log Writer issues a commit record in the redo log buffer and writes it to disk immediately, along with the transaction’s redo entries. The corresponding changes to data blocks are delayed until it is more efficient to write them. This is called a fast commit mechanism.

39. What Is Database Writer Process?

It writes the contents of buffers to data files.The DBWn processes are responsible for writing modified buffers in the database buffer cache to disk.

However one database writer process (DBW0) is enough for most systems, you can configure other processes (DBW1 through DBW9 and DBWa through DBWj) to improve write performance if your system manipulates data very much. These additional DBWn processes are not useful on uniprocessor systems.

40. What Are The Processes Does Background Processes In An Oracle Includes?

The background processes in an Oracle instance can include the following

Database Writer Process (DBWn)

Log Writer Process (LGWR)

Checkpoint Process (CKPT)

System Monitor Process (SMON)

Process Monitor Process (PMON)

Recoverer Process (RECO)

Job Queue Processes

Achiever Processes (ARCn)

Queue Monitor Processes (QMNn)

41. What Are Background Processes In Oracle?

In order to enhance performance and accommodate many users, a multi-process Oracle system uses some additional Oracle processes called background processes.

42. What Server Processes Can Perform Created On Behalf Of Each User’s Application?

Server processes can perform one or more of the following

Parses and executes SQL statements fired through the application.

Reads data blocks from datafiles on disk into the shared database buffers of the System Global Area, if the blocks are not already present in the System Global Area.

Return results in such a way that the application can process the information

43. What Are Server Processes In Oracle?

Oracle creates server processes to serve user processes requests, connected to the instance. In some situations, when the application and Oracle are on the same system, it is possible to combine the user process and corresponding server process into one process for reducing system overhead. However, when the application and Oracle operate on different computers, a user process always talks to Oracle through a separate server process.


44. What Are Dedicated And Shared Server Process?

Server Configurations

Dedicated server process

Shared server process

The server process created on behalf of each user process is called a dedicated server process (or shadow process).Shared server architecture removes the need for a dedicated server process for each connection.

A dispatcher routes multiple incoming network session requests to a pool of shared server processes.

An idle shared server process from a pool of shared server processes picks up a request from a common queue, which does mean a small number of shared servers can do the same amount of processing as many dedicated servers.

45. What Are The Contents Of Pga?

Content of the Program Global Area  The content of the Program Global Area memory varies, depending on whether the instance is running the shared server option. But in general, the PGA memory can be classified in the following manner.

Private SQL Area  A private SQL area contains information such as bind information and runtime memory structures.

Cursors and SQL Areas  Session memory is the memory assigned to hold a session's variables (logon information) and other session information. The session memory is shared and not private for a shared server.

SQL Work Areas For complex queries such as decision-support queries, a big portion of the runtime area is dedicated to work areas allocated by memory- intensive operators.

46. What Is Pga?

A PGA i.e Program Global Area is a memory region that contains data and control information for a server process.It is a memory created by Oracle when a server process is started and it is non shared. Access to it is exclusive to that server process and is read and written by Oracle code.

The total PGA memory allocated by each server process associated to an Oracle instance is also known as aggregated PGA memory allocated by the instance.

47. What Is Shared Pool?

The Shared Pool part of the System Global Area contains the library cache, the dictionary cache, buffers for parallel execution messages, and control structures.

48. What Is Redo Log Buffer?

The Redo Log Buffer is a circular buffer in the System Global Area that holds information about changes made to the database. Redo entries contain the information to reconstruct, or redo, changes made to the database by INSERT, UPDATE, DELETE, CREATE, ALTER, or DROP operations. Redo entries are used for database recovery, if necessary.

49. What Are Database Buffers?

It is the portion of the System Global Area that holds copies of data blocks read from datafiles. All user processes are connected to the instance concurrently and share access to the database buffer cache.

50. What Are The Data Structures Does Sga Contains?

The SGA contains the following data structures

Database buffer cache

Redo log buffer

Shared pool

Java pool

Large pool (optional)

Streams pool

Data dictionary cache

Other miscellaneous information

51. What Is Difference Between C And C++?

C++ is Multi-Paradigm ( not pure OOP, supports both procedural and object oriented) while C follows procedural style programming.

In C data security is less, but in C++ you can use modifiers for your class members to make it inaccessible from outside.

C follows top-down approach ( solution is created in step by step manner, like each step is processed into details as we proceed ) but C++ follows a bottom-up approach ( where base elements are established first and are linked to make complex solutions ).

C++ supports function overloading while C does not support it.

C++ allows use of functions in structures, but C does not permit that.

C++ supports reference variables ( two variables can point to same memory location ). C does not support this.

C does not have a built in exception handling framework, though we can emulate it with other mechanism. C++ directly supports exception handling, which makes life of developer easy.

52. What Is A Class?

Class defines a datatype, it's type definition of category of thing(s). But a class actually does not define the data, it just specifies the structure of data. To use them you need to create objects out of the class. Class can be considered as a blueprint of a building, you can not stay inside blueprint of building, you need to construct building(s) out of that plan. You can create any number of buildings from the blueprint, similarly you can create any number of objects from a class.

class Vehicle



        int numberOfTyres;

        double engineCapacity;

        void drive(){

            // code to drive the car



53. What Is An Object/instance?

Object is the instance of a class, which is concrete. From the above example, we can create instance of class Vehicle as given below Vehicle vehicleObject;

We can have different objects of the class Vehicle, for example we can have Vehicle objects with 2 tyres, 4tyres etc. Similarly different engine capacities as well.

54. What Do You Mean By C++ Access Specifiers?

Access specifiers are used to define how the members (functions and variables) can be accessed outside the class. There are three access specifiers defined which are public, private, and protected

Private Members declared as private are accessible only with in the same class and they cannot be accessed outside the class they are declared.

Public Members declared as public are accessible from anywhere.

Protected Members declared as protected cannot be accessed from outside the class except a child class. This access specified has significance in the context of inheritance.

55. What Are The Basics Concepts Of Oop?

Encapsulation  Encapsulation is the mechanism by which data and associated operations/methods are bound together and thus hide the data from outside world. It's also called data hiding. In c++, encapsulation achieved using the access specifiers (private, public and protected). Data members will be declared as private (thus protecting from direct access from outside) and public methods will be provided to access these data. Consider the below class

class Person



      int age;


      int getAge(){

        return age;


      int setAge(int value){

        if(value > 0){

            age = value;




In the class Person, access to the data field age is protected by declaring it as private and providing public access methods. What would have happened if there was no access methods and the field age was public? Anybody who has a Person object can set an invalid value (negative or very large value) for the age field. So by encapsulation we can preventing direct access from outside, and thus have complete control, protection and integrity of the data.

Data abstraction  Data abstraction refers to hiding the internal implementations and show only the necessary details to the outside world. In C++ data abstraction is implemented using interfaces and abstract classes.

class Stack



        virtual void push(int)=0;

        virtual int pop()=0;


class MyStack  public Stack



        int arrayToHoldData[]; //Holds the data from stack


        void push(int) {

            // implement push operation using array


        int pop(){

            // implement pop operation using array



In the above example, the outside world only need to know about the Stack class and its push, pop operations. Internally stack can be implemented using arrays or linked lists or queues or anything that you can think of. This means, as long as the push and pop method performs the operations work as expected, you have the freedom to change the internal implementation with out affecting other applications that use your Stack class.

Inheritance  Inheritance allows one class to inherit properties of another class. In other words, inheritance allows one class to be defined in terms of another class.

class SymmetricShape



        int getSize()


            return size;


        void setSize(int w)


            size = w;



        int size;


// Derived class

class Square public SymmetricShape



        int getArea()


            return (size * size);




In the above example, class Square inherits the properties and methods of class SymmetricShape. Inheritance is the one of the very important concepts in C++/OOP. It helps to modularise the code, improve reusability and reduces tight coupling between components of the system.

56. What Is The Use Of Volatile Keyword In C++? Give An Example.

Most of the times compilers will do optimization to the code to speed up the program. For example in the below code,

int a = 10;

while( a == 10){

     // Do something


compiler may think that value of 'a' is not getting changed from the program and replace it with 'while(true)', which will result in an infinite loop. In actual scenario the value of 'a' may be getting updated from outside of the program.

Volatile keyword is used to tell compiler that the variable declared using volatile may be used from outside the current scope so that compiler wont apply any optimization. This matters only in case of multi-threaded applications.

In the above example if variable 'a' was declared using volatile, compiler will not optimize it. In shot, value of the volatile variables will be read from the memory location directly.




57. In How Many Ways We Can Initialize An Int Variable In C++?

In c++, variables can be initialized in two ways, the traditional C++ initialization using "=" operator and second using the constructor notation.

Traditional C++ initilization

int i = 10;

variable i will get initialized to 10.

Using C++ constructor notation

int i(10);

58. What Is Implicit Conversion/coercion In C++?

Implicit conversions are performed when a type (say T) is used in a context where a compatible type (Say F) is expected so that the type T will be promoted to type F.

short a = 2000 + 20;

In the above example, variable a will get automatically promoted from short to int. This is called implicit conversion/coercion in c++.

59. What Are C++ Inline Functions?

C++ inline functions are special functions, for which the compiler replaces the function call with body/definition of function. Inline functions makes the program execute faster than the normal functions, since the overhead involved in saving current state to stack on the function call is avoided. By giving developer the control of making a function as inline, he can further optimize the code based on application logic. But actually, it's the compiler that decides whether to make a function inline or not regardless of it's declaration. Compiler may choose to make a non inline function inline and vice versa. Declaring a function as inline is in effect a request to the compiler to make it inline, which compiler may ignore. So, please note this point for the interview that, it is upto the compiler to make a function inline or not.

inline int min(int a, int b)


   return (a < b)? a  b;


int main( )


   cout << "min (20,10) " << min(20,10) << endl;

   cout << "min (0,200) " << min(0,200) << endl;

   cout << "min (100,1010) " << min(100,1010) << endl;

   return 0;


If the complier decides to make the function min as inline, then the above code will internally look as if it was written like

int main( )


   cout << "min (20,10) " << ((20 < 10)? 20  10) << endl;

   cout << "min (0,200) " << ((0 < 200)? 0  200) << endl;

   cout << "min (100,1010) " << ((100 < 1010)? 100  1010) << endl; 

 return 0;


60. What Do You Mean By Translation Unit In C++?

We organize our C++ programs into different source files (.cpp, .cxx etc). When you consider a source file, at the preprocessing stage, some extra content may get added to the source code ( for example, the contents of header files included) and some content may get removed ( for example, the part of the code in the #ifdef of #ifndef block which resolve to false/0 based on the symbols defined). This effective content is called a translation unit. In other words, a translation unit consists of Contents of source file Plus contents of files included directly or  indirectly Minus source code lines ignored by any conditional pre processing directives ( the lines ignored by #ifdef,#ifndef etc)

61. What Do You Mean By Internal Linking And External Linking In C++?

A symbol is said to be linked internally when it can be accessed only from with-in the scope of a single translation unit. By external linking a symbol can be accessed from other translation units as well. This linkage can be controlled by using static and extern keywords.

62. What Do You Mean By Storage Classes?

Storage class are used to specify the visibility/scope and life time of symbols(functions and variables). That means, storage classes specify where all a variable or function can be accessed and till what time those variables will be available during the execution of program.

63. What Are The Difference Between Reference Variables And Pointers In C++?


Pointers can be assigned to NULL

Pointers can be (re)pointed to any object, at any time, any number of times during the execution.

Pointer has own memory address and location on stack

Reference Variables

References cannot be assigned NULL. It should always be associated with actual memory, not NULL.

Reference variables should be initialized with an object when they are created and they cannot be reinitialized to refer to another object

Reference variables has location on stack, but shares the same memory location with the object it refer to.

64. What Is Meant By Reference Variable In C++?

In C++, reference variable allows you create an alias (second name) for an already existing variable. A reference variable can be used to access (read/write) the original data. That means, both the variable and reference variable are attached to same memory location. In effect, if you change the value of a variable using reference variable, both will get changed (because both are attached to same memory location).

65. How To Create A Reference Variable In C++?

Appending an ampersand (&) to the end of datatype makes a variable eligible to use as reference variable.

int a = 20;

int& b = a;

The first statement initializes a an integer variable a. Second statement creates an integer reference initialized to variable a Take a look at the below example to see how reference variables work.

int main ()


int   a;

int&  b = a;

a = 10;

cout << "Value of a  " << a << endl;

cout << "Value of a reference (b)  " << b  << endl;

b = 20;

cout << "Value of a  " << a << endl;

cout << "Value of a reference (b)  " << b  << endl;

return 0;


Above code creates following output.

Value of a  10

Value of a reference (b)  10

Value of a  20

Value of a reference (b)  20

66. What You Mean By Early Binding And Late Binding? How It Is Related To Dynamic Binding?

Binding is the process of linking actual address of functions or identifiers to their reference. This happens mainly two times.

During compilation  This is called early binding

 For all the direct function references compiler will replace the reference with actual address of the method.

At runtime  This is called late binding.

In case of virtual function calls using a Base reference, compiler does not know which method will get called at run time. In this case compiler will replace the reference with code to get the address of function at runtime.

Dynamic binding is another name for late binding.

67. What Is Virtual Destructor? Why They Are Used?

Virtual destructors are used for the same purpose as virtual functions. When you remove an object of subclass, which is referenced by a parent class pointer, only destructor of base class will get executed. But if the destructor is defined using virtual keyword, both the destructors [ of parent and sub class ] will get invoked.

68. Why Pure Virtual Functions Are Used If They Don't Have Implementation / When Does A Pure Virtual Function Become Useful?

Pure virtual functions are used when it doesn't make sense to provide definition of a virtual function in the base class or a proper definition does not exists in the context of base class. Consider the above example, class SymmetricShape is used as base class for shapes with symmetric structure(Circle, square, equilateral triangle etc). In this case, there exists no proper definition for function draw() in the base class SymmetricShape instead the child classes of SymmetricShape (Cirlce, Square etc) can implement this method and draw proper shape.

69. How To Create A Pure Virtual Function?

A function is made as pure virtual function by the using a specific signature, " = 0" appended to the function declaration as given below,

class SymmetricShape {


        // draw() is a pure virtual function.

        virtual void draw() = 0;


70. What Do You Mean By Pure Virtual Functions In C++? Give An Example?

 Pure virtual function is a function which doesn't have an implementation and the same needs to be implemented by the the next immediate non-abstract class. (A class will become an abstract class if there is at-least a single pure virtual function and thus pure virtual functions are used to create interfaces in c++).

71. What Are Virtual Functions And What Is Its Use?

Virtual functions are member functions of class which is declared using keyword 'virtual'. When a base class type reference is initialized using object of sub class type and an overridden method which is declared as virtual is invoked using the base reference, the method in child class object will get invoked.

class Base


    int a;




            a = 1;


        virtual void method()


            cout << a;



class Child public Base


    int b;




            b = 2;


        virtual void method()


            cout << b;



int main()


    Base *pBase;

    Child oChild;

    pBase = &oChild;


    return 0;


In the above example even though the method in invoked on Base class reference, method of the child will get invoked since its declared as virtual.

72. How Many Storage Classes Are Available In C++?

Storage class are used to specify the visibility/scope and life time of symbols(functions and variables). That means, storage classes specify where all a variable or function can be accessed and till what time those variables will be available during the execution of program.

Following storage classes are available in C++

auto  It's the default storage class for local variables. They can be accessed only from with in the declaration scope. auto variables are allocated at the beginning of enclosing block and deallocated at the end of enclosing block.

register  It's similar to auto variables. Difference is that register variables might be stored on the processor register instead of RAM, that means the maximum size of register variable should be the size of CPU register ( like 16bit, 32bit or 64bit). This is normally used for frequently accessed variables like counters, to improve performance. But note that, declaring a variable as register does not mean that they will be stored in the register. It depends on the hardware and implementation.

static  A static variable will be kept in existence till the end of the program unlike creating and destroying each time they move into and out of the scope. This helps to maintain their value even if control goes out of the scope. When static is used with global variables, they will have internal linkage, that means it cannot be accessed by other source files. When static is used in case of a class member, it will be shared by all the objects of a class instead of creating separate copies for each object.

extern extern is used to tell compiler that the symbol is defined in another translation unit (or in a way, source files) and not in the current one. Which means the symbol is linked externally. extern symbols have static storage duration, that is accessible through out the life of program. Since no storage is allocated for extern variable as part of declaration, they cannot be initialized while declaring.

mutable  mutable storage class can be used only on non static non const data a member of a class. Mutable data member of a class can be modified even is it's part of an object which is declared as const.

73. What Is 'copy Constructor' And When It Is Called?

Copy constructor is a special constructor of a class which is used to create copy of an object. Compiler will give a default copy constructor if you don't define one. This implicit constructor will copy all the members of source object to target object.

Implicit copy constructors are not recommended, because if the source object contains pointers they will be copied to target object, and it may cause heap corruption when both the objects with pointers referring to the same location does an update to the memory location. In this case its better to define a custom copy constructor and do a deep copy of the object.

        class SampleClass{


                int* ptr;


                // Copy constructor declaration

                SampleClass(SampleClass &obj);



            ptr = new int();

            *ptr = 5;


        // Copy constructor definition

        SampleClassSampleClass(SampleClass &obj){

            //create a new object for the pointer

            ptr = new int();

            // Now manually assign the value

            *ptr = *(obj.ptr);

            cout<<"Copy constructor...n";


74. What Is Realloc() And Free()? What Is Difference Between Them?

void* realloc (void* ptr, size_t size)  This function is used to change the size of memory object pointed by address ptr to the size given by size. If ptr is a null pointer, then realloc will behave like malloc(). If the ptr is an invalid pointer, then defined behaviour may occur depending the implementation. Undefined behaviour may occur if the ptr has previously been deallocated by free(), or dealloc() or ptr do not match a pointer returned by an malloc(), calloc() or realloc().

void free (void* ptr)  This function is used to deallocate a block of memory that was allocated using malloc(), calloc() or realloc(). If ptr is null, this function does not doe anything.

75. What Is Difference Between Shallow Copy And Deep Copy? Which Is Default?

 When you do a shallow copy, all the fields of the source object is copied to target object as it is. That means, if there is a dynamically created field in the source object, shallow copy will copy the same pointer to target object. So you will have two objects with fields that are pointing to same memory location which is not what you usually want.

In case of deep copy, instead of copying the pointer, the object itself is copied to target. In this case if you modify the target object, it will not affect the source. By default copy constructors and assignment operators do shallow copy. To make it as deep copy, you need to create a custom copy constructor and override assignment operator.

76. What Do You Mean By Persistent And Non Persistent Objects?

Persistent objects are the ones which we can be serialized and written to disk, or any other stream. So before stopping your application, you can serialize the object and on restart you can deserialize it. [ Drawing applications usually use serializations.]

Objects that can not be serialized are called non persistent objects. [ Usually database objects are not serialized because connection and session will not be existing when you restart the application. ]

77. Is It Possible To Get The Source Code Back From Binary File?

Technically it is possible to generate the source code from binary. It is called reverse engineering. There are lot of reverse engineering tools available. But, in actual case most of them will not re generate the exact source code back because many information will be lost due to compiler optimization and other interpretations.

78. What Is The Difference Between #include <file> And #include "file" ?

We use # include to include a file. The difference between two ways of file inclusion lies in the order in which preprocessor searches for the file specified. When the preprocessor encounters #include<file> statement, it looks for the file specified in the angled brackets in the default location (Path defined in INCLUDE environment variable of the system).

When # include followed by file name in double quotation marks is encountered by the preprocessor, it looks for the file in the current directory. If the file is not found in the current directory, it will look for the file in the default location.

79. Can #include Handle Other File Formats Than .h?

Yes. Irrespective of the file type, Preprocessor will do its job and will include any file like test.z.

80. What Is A Void Pointer?

A void pointer is a special pointer type which can point to any data type without letting the compiler know. It helps to pass a pointer to some function of any type which can be decided at run time. In the following example input parameter a and b can be both integer and string.

Void PointerVoid(int type, void *a, void *b, void *c)


   if(type == 1)/* int*/

   *c = ((int) *a) + ((int)*b);

   else /*string*/



81. What Is The Value Of Null?

The value of NULL is 0 or (void*)0. Whenever NULL has to be compared with some variable or assigned to a variable, depending upon the type of that variable, the value of NULL will be decided

82. Can The Size Of An Array Be Declared At Runtime?

No. The size of an array must be stated at the time of compilation. Alternate way is to use dynamic allocation by calloc or malloc.

83. What Is The Difference Between Malloc() And Calloc()?


Allocates a region of memory large enough to hold "n” elements of "size" bytes each.

Calloc initializes the whole memory with 0


Allocates "size" bytes of memory.

Malloc does not change the existing memory. So it returns a memory chunk with garbage value.

84. What Is The Heap In Memory?

The heap is where malloc(), calloc(), and realloc() get memory. The allocation of memory from the heap is much slower than the stack. But, the heap is much more flexible about memory allocation than the stack. Memory can be allocated and deallocated in any time and order. This heap memory isn't deallocated by itself, method free() has to be called in order to do so.

85. What Will Be The Output Of The Following Code Snippet?

float num1 = 6 / 4;

float num2 = 6 / 4.0;

printf("6/4 == %f or %fn", num1, num2);

Output will be  6/4 == 1.000000 or 1. 500000. This is a case of operator promotion. The variable num1 is set to “6/4”. Because, both 3 and 4 are integers. So integer division is performed on them and the result is the integer 0. The variable num2 is set to “6/4.0”. Because 4.0 is a float, the number 6 is converted to a float as well, and the result will be floating value 1.5.

86. What Happens If You Free A Pointer Twice?


It is really dangerous to free the same memory twice. If the memory has not been reallocated in between, it will generate a “double free” error, since the memory location has already been freed.

87. How Does Free() Method Know About How Much Memory To Release?

There's no concrete way. Most systems, keeps a track of each memory block as linked lists. When memory is allocated, all the blocks that are given to that particular call are put into a linked list and the size, block number and serial number are written in the head node. There is no assurance, though. But in some way or other, the system keeps track of each block to know the size of each allocated portion of the heap

88. How To Restrict A Header File From Including More Than Once?

 In C, to avoid double inclusion, we use a include guard also known as macro guard. It is #ifndef - #endif pair. "ifndef" is an indication of “if not defined”.

#ifndef FAMILY_H

#define FAMILY_H

struct Example


  int member;


#endif /* FAMILY _H */

89. How To Print An Address?

 The best way is to use "%p" in printf() or fprintf. The “%p” will tell compiler to use the best type to use, while printing the address according to the environment, since the size of a pointer changes from system to system.

90. Explain Recursive Functions? Also Explain The Advantages And Disadvantages Of Recursive Algorithms?

A recursive function is a function which calls itself.

The advantages of recursive functions are

A substitute for very complex iteration. For example, a recursive function is best to reduce the code size for Tower of Hanoi application.

Unnecessary calling of functions can be avoided.

The disadvantages of Recursive functions

The exit point must be explicitly coded ,otherwise stack overflow may happen

A recursive function is often confusing. It is difficult to trace the logic of the function. Hence, it is difficult to debug a recursive function.

91. What Are The Standard Predefined Macros?

ANSI C has six predefined macro. They are

__FILE__ - Name of the current file

__LINE__ - Current line number

__TIME__ - Current time of compilation

__DATE__ - Current date of compilation

__cplusplus - If program compiled in C++ compiler

__STDC__ - If ANSI C is followed by the compiler strictly.

92. What Is A Pragma?

 The #pragma preprocessor allows compiler to include or exclude compiler specific features. For example if there is a feature xxx_yyy then,

#pragma xxx_yyy(on)

Forces compiler to include the feature. Conversely, you can turn off it by the following lines

#pragma xxx_yyy(off)

93. How To Redefined Macro With Different Value?

 The #undef preprocessor can be used to reset a macro. For example,

#ifdef SAMPLE /* Checking if SAMPLE is defined */

#undef SAMPLE /* If so, then reset it */


#define SAMPLE 0 /* Then redefine with intended value */

94. What Is An Lvalue?

An lvalue is an expression to which a value can be assigned. The lvalue expression is the one which is located on the left side a statement, whereas an rvalue is located on the right side of a statement. Each assignment must have a valid lvalue and rvalue. The lvalue expression must refer to a storage where something can be stored. It can't be a constant.

95. How To Assign One Array To Another?

You can't assign an array to other. Arrays are not lvalue, because they don't refer to one variable, rather a set of variables. So they can't be placed on the left hand side of an assignment statement. For example the following statement will generate compilation error.

int x[5], y[5];

x = y;

96. What Is The Order Of Operator Precedence, Left To Right Or Right To Left ?

None of them is standard. C does not always start evaluating left to right or right to left. Normally, function calls are done first, followed by complex expressions and then simple expressions. That is why it is best to use parenthesis in all expressions, without depending on precedence.

97. What Is The Difference Between ++x And X++?

The ++ operator is called the incremental operator. When the operator is placed before, the variable is incremented by 1 before it is used in the statement. When the operator is placed after the variable, then the expression is evaluated first and then the variable is incremented by 1.

98. What Happens When We Use Incremental Operator In A Pointer?

It depends upon the type of the pointer. It gets incremented by the size of the data type, the pointer is pointing to. For example

char p; p++; /* here p increments by 1*/

int p; p++;/* here p increments by 4(for 32 bit system)*/

99. Can The Sizeof Operator Be Used To Tell The Size Of An Array Passed To A Function?

No. The sizeof() operator can't tell the size of an array, because it is actually a pointer to the data type of the array.

100. Can You Change The Value Of An Array Tag?

No. An array tag can't be used as a storage, because it is not an Lvalue. It can be thought as a pointer to the datatype of the array which is constant and which can't be changed or assigned dynamically.

101. What Are Text And Binary Modes?

Streams can be classified into two types text streams and binary streams. The text streams are interpreted as per the ASCII values starting from 0 to 255. Binary streams are raw bytes which C can't interpret, but application has to interpret it itself. Text modes are used to handle, generally text file where as binary modes can be used for all files. But they won't give you the content of a file, rather they will give you the file properties and content in raw binary format.

102. Which One To Use, A Stream Function Or A System Calls?

Stream files are generally better to use, since they provide sufficient amount of buffer for read and write. That is why it is more efficient.

But in a multiuser environment, files can be shared among users. These shared files are secured with lock, where only one user will be able to write at a time. In this scenario, buffering will not be efficient, since the file content will change continuously and it will be slower.

So, normally it is good to use stream functions, but for shared files system calls are better.

103. What Is The Difference Between A String Copy (strcpy) And A Memory Copy (memcpy)?

Generally speaking, they both copy a number of bytes from a source pointer to a destination pointer. But the basic difference is that the strcpy() is specifically designed to copy strings, hence it stops copying after getting the first ''(NULL) character. But memcpy() is designed to work with all data types. So you need to specify the length of the data to be copied, starting from the source pointer.

104. How Can I Pad A String To A Known Length?

printf("%-20.20s", data[d]);

The "%-20.20s" argument tells the printf() function that you are printing a string and you want to force it to be 20 characters long. By default, the string is right justified, but by including the minus sign (-) before the first 20, you tell the printf() function to left-justify your string. This action forces the printf() function to pad the string with spaces to make it 20 characters long.

105. What Does Const Keyword Do?


The access modifier keyword “const” tells compiler that the value of this variable is not going to be changed after it is initialized. The compiler will enforce it throughout the lifetime of the variable.

106. Char *p="sampletext" , *q ="sampletext"; Are These Two Pointers Equal ? If Yes , Then Explain?

In C, strings(not array of characters) are immutable. This means that a string once created cannot be modified. Only flushing the buffer can remove it. Next point is, when a string is created it is stored in buffer. Next time, when a new string is created, it will check whether that string is present in buffer or not. If present, that address is assigned. Otherwise, new address stores the new string and this new address is assigned.

107. When Should A Type Cast Be Used?

There are two main uses of type cast.

The first one is to convert some value of datatype A to a datatype B. Such as, if you type cast a float variable of value 1.25 to int, then it will be 1.

The second use is to cast any pointer type to and from void *, in order to use it in generic functions such as memory copy functions, where the execution is independent of the type of the pointer.

108. What Is The Difference Between Declaring A Variable And Defining A Variable?

Declaration is done to tell compiler the data type of the variable, and it inherently meant that somewhere in this scope, this variable is defined or will be defined. And defining a variable means to allocate space for that variable and register it in the stack memory. For example

extern int decl1; /* this is a declaration */

int def2; /* this is a definition */

109. Can Static Variables Be Declared In A Header File?

You can't declare a static variable without definition (this is because they are mutually exclusive storage classes). A static variable can be defined in a header file, but then every source file with in that scope will have their own copy of this variable, which is intended.

110. What Is The Benefit Of Using Const For Declaring Constants Over #define?

The basic difference between them is that, a const variable is a real variable which has a datatype and it exists at run time, and it can't be altered. But a macro is not a real variable, but it carries a constant value which replaces all the occurrences of that macro at the time of pre-processing.

111. What Is A Static Function?

Static function is a special type of function whose scope is limited to the source file where the function is defined and can not be used other than that file. This feature helps you to hide some functions and to provide some standard interface or wrapper over that local function.

112. Should A Function Contain A Return Statement If It Does Not Return A Value?


In C, void functions does not return anything. So it is useless to put a return statement at the end of the function, where the control will any way return to the caller function. But, if you want to omit some portion of the function depending upon the scenario, then this return statement is perfect to avoid further execution of that void function.

113. How Can You Pass An Array To A Function By Value?

An array can be passed to a function by value, by keeping a parameter with an array tag with empty square brackets(like []). From the caller function, just pass the array tag. For instance,

void func(int i[]) {..} /* parameter */


int k[10];

func(k); /* caller function */

114. Is It Possible To Execute Code Even After The Program Exits The Main() Function?

There is a standard C function named atexit() for this purpose that can be used to perform some operations when your program exiting. You can register some functions with atexit() to be executed at the time of termination. Here's an example

#include <stdio.h>

#include <stdlib.h>

void _some_FUNC_(void);

int main(int argc, char** argv)






115. What Does A Function Declared As Pascal Do Differently?

In C, when some function is called, the parameters are put at the top of the stack. Now the order in which they are put is the order in which the parameters are parsed. Normally, the order is right to left. That is, the right most is parsed first and the left most parameter is parsed at last.

If you want to alter this paradigm, then you have to define the function with PASCAL as following

int PASCAL pascal_func(int, char*, long);

Here, the left most parameter(int) will be parsed first, then char* and then long.

116. Why Does Pascal Matter? Is There Any Benefit To Using Pascal Functions?

The main reason behind using PASCAL is that, in the left-to-right parsing the efficiency of switching increases in C.

117. Is Using Exit() The Same As Using Return?

No. They are not the same. Return statement returns control to the caller function, that is, it exits from the lowest level of the call stack. Where as, exit statement make the program returns to the system from where the application was started. So, exit always exits from the highest level of call stack. Eventually, if there is only one level of function call then they both do the same.

118. In C, What Is The Difference Between A Static Variable And Global Variable?

A static variable ia declared outside of any function and it is accessible only to all the functions defined in the same file (as the static variable). In case of global variable, it can be accessed by any function (including the ones from different files).

119. Write A C Program To Swap Two Variables Without Using Third Variable ?


int main()


  int a=5,b=10;




  printf("a= %d b= %d",a,b);


120. What Is Dangling Pointer In C?

If any pointer is pointing at the memory location/address of any variable, but if the variable is deleted or does not exist in the current scope of code, while pointer is still pointing to that memory location, then the pointer is called dangling pointer. For example,


int *func();

int main()


  int *ptr;



  return 0;


int * func()


  int x=18;

  return &x;


Output is Garbage value, since the variable x has been freed as soon as the function func() returned

121. What Is Wild Pointer In C?

A pointer is known as wild pointer c, if it has not been initialized. For Example

int main()


  int *ptr;



  return 0;


Output Any address, Garbage value.

Here ptr is wild pointer, because it has not been initialized. Wild pointer is not the same as NULL pointer. Because, NULL pointer doesn't point to any location, but a wild pointer points to a specific memory location but the memory may not be available for current application, which is very fatal.

122. What Is The Meaning Of Prototype Of A Function?

Declaration of function is known as prototype of a function. Prototype says the name, parameter list and return type of a function but not the definition, this is same as declaring some variable but not defining it. For example,

int printf(const char *, int/);

123. Write A C Program To Find Size Of Structure Without Using Sizeof Operator?

struct XXX


  int x;

  float y;

  char z;


int main()


  struct XXX *ptr=(struct XXX *)0;


  printf("Size of structure is %d",*ptr);

  return 0;


124. What Is Size Of Void Pointer?

Size of all pointers are same in C, regardless of their type because pointers variable holds a memory location. And for a given system, this size is constant. The type of pointer is used to know the size of the data that the pointer is pointer is pointing to.

125. How Do You Use A Pointer To A Function?

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 as shown below

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

Notice that you need to put parentheses around *pf.