PHP INTERVIEW TIPS Part-1

What's PHP ?


The PHP Hypertext Preprocessor is a programming language that allows web developers to create dynamic content that interacts with databases. PHP is basically used for developing web based software applications.

What Is a Session?


A session is a logical object created by the PHP engine to allow you to preserve data across subsequent HTTP requests.
There is only one session object available to your PHP scripts at any time. Data saved to the session by a script can be retrieved by the same script or another script when requested from the same visitor.
Sessions are commonly used to store temporary data to allow multiple PHP pages to offer a complete functional transaction for the same visitor.

What is meant by PEAR in php?


Answer1:
PEAR is the next revolution in PHP. This repository is bringing higher level programming to PHP. PEAR is a framework and distribution system for reusable PHP components. It eases installation by bringing an automated wizard, and packing the strength and experience of PHP users into a nicely organised OOP library. PEAR also provides a command-line interface that can be

Read More ->>

Oracle DBA interview Tips Part 4

Database Security & Administration
97. What is user Account in Oracle database?
A user account is not a physical structure in database but it is having important relationship to the objects in the database and will be having certain privileges.
98. How will you enforce security using stored procedures?
Don't grant user access directly to tables within the application.
Instead grant the ability to access the procedures that access the tables.
When procedure executed it will execute the privilege of procedures owner. Users cannot access tables except via the procedure.
99. What are the dictionary tables used to monitor a database space?
DBA_FREE_SPACE
DBA_SEGMENTS
DBA_DATA_FILES.
SQL*Plus Statements
100. What are the types of SQL statement?
Data Definition Language: CREATE, ALTER, DROP, TRUNCATE, REVOKE, NO AUDIT & COMMIT.
Data Manipulation Language: INSERT, UPDATE, DELETE, LOCK TABLE, EXPLAIN PLAN & SELECT.
Transactional Control: COMMIT & ROLLBACK
Session Control: ALTERSESSION & SET ROLE
System Control: ALTER SYSTEM.
101. What is a transaction?
Transaction is logical unit between two commits and commit and rollback.
102. What is difference between TRUNCATE & DELETE?

Read More ->>

Oracle DBA interview Tips Part 3

Database Logical & Physical Architecture
64. What is Database Buffers?
Database buffers are cache in the SGA used to hold the data blocks that are read from the data segments in the database such as tables, indexes and clusters DB_BLOCK_BUFFERS parameter in INIT.ORA decides the size.
65. What is dictionary cache?
Dictionary cache is information about the database objects stored in a data dictionary table.
66. What is meant by recursive hints?
Number of times processes repeatedly query the dictionary table is called recursive hints. It is due to the data dictionary cache is too small. By increasing the SHARED_POOL_SIZE parameter we can optimize the size of data dictionary cache.
67. What is redo log buffer?

Read More ->>

Oracle DBA interview Tips Part 2

37. What is a segment?
A segment is a set of extents allocated for a certain logical structure.
38. What are the different types of segments?
Data segment, index segment, rollback segment and temporary segment.
39. What is a data segment?
Each non-clustered table has a data segment. All of the table's data is stored in the extents of its data segment. Each cluster has a data segment. The data of every table in the cluster is stored in the cluster's data segment.
40. What is an index segment?
Each index has an index segment that stores all of its data.
41. What is rollback segment?
A database contains one or more rollback segments to temporarily store "undo" information.
42. What are the uses of rollback segment?

Read More ->>

Oracle DBA interview Tips Part 1

Oracle Concepts and Architecture Database Structures1. What are the components of physical database structure of Oracle database?
Oracle database is comprised of three types of files. One or more datafiles, two are more redo log files, and one or more control files.
2. What are the components of logical database structure of Oracle database?
There are tablespaces and database's schema objects.
3. What is a tablespace?
A database is divided into Logical Storage Unit called tablespaces. A tablespace is used to grouped related logical structures together.
4. What is SYSTEM tablespace and when is it created?

Read More ->>

J2EE Interview Tips Part 7

301. What is transaction isolation level

What is transaction isolation level The degree to which the intermediate state of the data being modified by a transaction is visible to other concurrent transactions and data being modified by other transactions is visible to it.

302. What is transaction manager

Provides the services and management functions required to support transaction demarcation, transactional resource management, synchronization,
and transaction context propagation.

303. What is Unicode ?

Read More ->>

J2EE Interview Tips Part 6

251. What is renderer

A Java class that can render the output for a set of JavaServer Faces UI components.

252. What is request-response messaging

A method of messaging that includes blocking until a response is received.


253. What is resource adapter

A system-level software driver that is used by an EJB container or an application client to connect to an enterprise information system. A resource adapter typically is specific to an enterprise information system. It is available as a library and is used within the address space of the server or client using it. A resource adapter plugs in to a container. The application components deployed on the container then use the client API (exposed by the adapter) or tool-generated high-level abstractions to access the underlying enterprise information system. The resource adapter and EJB container collaborate to provide the underlying mechanisms-transactions, security, and connection pooling-for connectivity to the enterprise information system.

254. What is resource adapter module ?

Read More ->>

J2EE Interview Tips Part 5

201. What is normalization

The process of removing redundancy by modularizing, as with subroutines, and of removing superfluous differences by reducing them to a common denominator.
For example, line endings from different systems are normalized by reducing them to a single new line, and multiple whitespace characters are normalized to one space.

202. What is North American Industry Classification
System (NAICS)

A system for classifying business establishments based on the processes they use to produce goods or services.

203. What is notation ?

Read More ->>

J2EE Interview Tips Part 4

151. What is JavaServer Pages Standard Tag Library
(JSTL)

A tag library that encapsulates core functionality common to many JSP applications. JSTL has support for common, structural tasks such as iteration and conditionals, tags for manipulating XML documents, internationalization and locale-specific formatting tags, SQL tags, and functions.

152. What is JAXR client

A client program that uses the JAXR API to access a business registry via a JAXR provider.

153. What is JAXR provider

An implementation of the JAXR API that provides access to a specific registry provider or to a class of registry providers that are based on a common specification.

154. What is JDBC ?

Read More ->>

J2EE Interview Tips Part 3

101. What is form-based authentication

An authentication mechanism in which a Web container provides an application-specific form for logging in. This form of authentication uses Base64 encoding and
can expose user names and passwords unless all connections are over SSL.

102. What is general entity

An entity that is referenced as part of an XML document's content, as distinct from a parameter entity, which is referenced in the DTD. A general entity can be a parsed entity or an unparsed entity.

103. What is group

An authenticated set of users classified by common traits such as job title or customer profile. Groups are also associated with a set of roles, and every user that is a member of a group inherits all the roles assigned to that group.

104. What is handle

An object that identifies an enterprise bean. A client can serialize the handle and then later deserialize it to obtain a reference to the enterprise bean.

105. What is home handle

An object that can be used to obtain a reference to the home interface. A home handle can be serialized and written to stable storage and deserialized to
obtain the reference.

107. What is home interface

One of two interfaces for an enterprise bean. The home interface defines zero or more methods for managing an enterprise bean. The home interface of a session bean
defines create and remove methods, whereas the home interface of an entity bean defines create, finder, and remove methods.

108. What is HTML

Hypertext Markup Language. A markup language for hypertext documents on the Internet. HTML enables the embedding of images, sounds, video streams, form
fields, references to other objects with URLs, and basic text formatting.

109. What is HTTP

Hypertext Transfer Protocol. The Internet protocol used to retrieve hypertext objects from remote hosts. HTTP messages consist of requests from client to
server and responses from server to client.

110. What is HTTPS

HTTP layered over the SSL protocol.

111. What is IDL

Interface Definition Language. A language used to define interfaces to remote CORBA objects. The interfaces are independent of operating systems and programming languages.

112. What is IIOP

Internet Inter-ORB Protocol. A protocol used for communication between CORBA object request brokers.

113. What is impersonation

An act whereby one entity assumes the identity and privileges of another entity without restrictions and without any indication visible to the recipients of
the impersonator's calls that delegation has taken place. Impersonation is a case of simple delegation.

114. What is initialization parameter

A parameter that initializes the context associated with a servlet

115. What is ISO 3166

The international standard for country codes maintained by the International Organization for Standardization (ISO).

116. What is ISV

Independent software vendor.

117. What is J2EE

Java 2 Platform, Enterprise Edition.


118. What is J2EE application

Any deployable unit of J2EE functionality. This can be a single J2EE module or a group of modules packaged into an EAR file along with a J2EE application deployment descriptor. J2EE applications are typically engineered to be distributed across multiple computing tiers.

119. What is J2EE component

A self-contained functional software unit supported by a container and configurable at deployment time. The J2EE specification defines the following J2EE components: Application clients and applets are components that run on the client. Java servlet and JavaServer Pages (JSP) technology components are Web components that run on the server. Enterprise JavaBeans (EJB) components (enterprise beans) are business components that run on the server. J2EE components are written in the Java programming language and are compiled in the same way as any program in the language. The difference between J2EE components and "standard" Java classes is that J2EE components are assembled into a J2EE application, verified to be well formed and in compliance with the J2EE specification, and deployed to production, where they are run and managed by the J2EE server or client container.

120. What is J2EE module

A software unit that consists of one or more J2EE components of the same container type and one deployment descriptor of that type. There are four types of modules: EJB, Web, application client, and resource adapter. Modules can be deployed as stand-alone units or can be assembled into a J2EE application.


121. What is J2EE product

An implementation that conforms to the J2EE platform specification.

122. What is J2EE product provider

A vendor that supplies a J2EE product.

123. What is J2EE server

The runtime portion of a J2EE product. A J2EE server provides EJB or Web containers or both.

124. What is J2ME

Abbreviate of Java 2 Platform, Micro Edition.

125. What is J2SE

Abbreviate of Java 2 Platform, Standard Edition.

126. What is JAR

Java archive. A platform-independent file format that permits many files to be aggregated into one file.


127. What is Java 2 Platform, Enterprise Edition(J2EE)

An environment for developing and deploying enterprise applications. The J2EE platform consists of a set of services, application programming interfaces (APIs),
and protocols that provide the functionality for developing multitiered, Web-based applications.

128. What is Java 2 Platform, Micro Edition (J2ME)

A highly optimized Java runtime environment targeting a wide range of consumer products, including pagers, cellular phones, screen phones, digital set-top boxes,
and car navigation systems.

129. What is Java 2 Platform, Standard Edition (J2SE)

The core Java technology platform.

130. What is Java API for XML Processing (JAXP)

An API for processing XML documents. JAXP leverages the parser standards SAX and DOM so that you can choose to parse your data as a stream of events or to build a tree-structured representation of it. JAXP supports the XSLT standard, giving you control over the presentation of the data and enabling you to convert the data to other XML documents or to other formats, such as HTML. JAXP provides namespace support, allowing you to work with schema that might otherwise have naming conflicts.


131. What is Java API for XML Registries (JAXR)

An API for accessing various kinds of XML registries.

132. What is Java API for XML-based RPC (JAX-RPC)

An API for building Web services and clients that use remote procedure calls and XML

133. What is Java IDL

A technology that provides CORBA interoperability and connectivity capabilities for the J2EE platform. These capabilities enable J2EE applications to invoke operations on remote network services using the Object Management Group IDL and IIOP.

134. What is Java Message Service (JMS)

An API for invoking operations on enterprise messaging systems.

135. What is Java Naming and Directory Interface(JNDI)

An API that provides naming and directory functionality.

136. What is Java Secure Socket Extension (JSSE)

A set of packages that enable secure Internet communications.

137. What is Java Transaction API (JTA)

An API that allows applications and J2EE servers to access transactions.

138. What is Java Transaction Service (JTS)

Specifies the implementation of a transaction manager that supports JTA and implements the Java mapping of the Object Management Group Object Transaction Service 1.1 specification at the level below the API.

139. What is JavaBeans component?

A Java class that can be manipulated by tools and composed into applications. A JavaBeans component must adhere to certain property and event interface conventions.

140. What is JavaMail?

An API for sending and receiving email.

141. What is JavaServer Faces Technology?

A framework for building server-side user interfaces for Web applications written in the Java programming language.

142. What is JavaServer Faces conversion model?

A mechanism for converting between string-based markup generated by JavaServer Faces UI components and server-side Java objects.

143. What is JavaServer Faces event and listener model?


A mechanism for determining how events emitted by
JavaServer Faces UI components are handled. This model
is based on the JavaBeans component event and listener
model.

144. What is JavaServer Faces _expression language?

A simple _expression language used by a JavaServer Faces UI component tag attributes to bind the associated component to a bean property or to bind the
associated component's value to a method or an external data source, such as a bean property. Unlike JSP EL expressions, JavaServer Faces EL expressions are evaluated by the JavaServer Faces implementation rather than by the Web container.

145. What is Java Server Faces navigation model?

A mechanism for defining the sequence in which pages in a JavaServer Faces application are displayed.

147. What is JavaServer Faces UI component?

A user interface control that outputs data to a client or allows a user to input data to a JavaServer Faces application.

148. What is JavaServer Faces UI component class

A JavaServer Faces class that defines the behavior and properties of a JavaServer Faces UI component.

149. What is JavaServer Faces validation model

A mechanism for validating the data a user inputs to a JavaServer Faces UI component.

150. What is JavaServer Pages (JSP)

An extensible Web technology that uses static data, JSP elements, and server-side Java objects to generate dynamic content for a client. Typically the static data is HTML or XML elements, and in many cases the client is a Web browser.

Read More ->>

J2EE Interview Tips Part 2

46. What is container?

An entity that provides life-cycle management, security, deployment, and runtime services to J2EE components. Each type of container (EJB, Web, JSP,
servlet, applet, and application client) also provides component-specific services.

47. What is container-managed persistence?

The mechanism whereby data transfer between an entity bean's variables and a resource manager is managed by the entity bean's container.

48. What is container-managed sign-on?

The mechanism whereby security information needed for signing on to a resource is supplied by the container.

49. What is container-managed transaction ?

Read More ->>

J2EE Interview Tips Part 1

1. What is J2EE?

J2EE is an environment for developing and deploying enterprise applications. The J2EE platform consists of a set of services, application programming interfaces
(APIs), and protocols that provide the functionality for developing multitiered, web-based applications.

2. What is the J2EE module?

A J2EE module consists of one or more J2EE components for the same container type and one component deployment descriptor of that type.

3. What are the components of J2EE application?

A J2EE component is a self-contained functional software unit that is assembled into a J2EE application with its related classes and files and communicates with other components. The J2EE specification defines the following J2EE components:

Read More ->>

C++ INTERVIEW TIPS Part 3

Question: Can we have "Virtual Constructors"?
Answer: No, we cannot have virtual constructors. But if the need arises, we can simulate the implementation of virtual constructor by calling a Init method from the constructor which, should be a virtual function.

Question: Explain the need for "Virtual Destructor".
Answer: In case of inheritance, objects should be destructed exactly the opposite way of their construction. If virtual keyword is not added before base class destructor declaration, then derived class destructor will not at all be called. Hence there will be memory leakage if allocated for derived class members while constructing the object.

Question: What will happen if I say delete this ?

Read More ->>

C++ INTERVIEW TIPS Part 2

Question: what is memory leaking in c++ ?
Answer: When a class uses dynamically allocated memory internally, all sorts of problems arise. If not properly used or handled, they can lead to memory leaks & corrupts Data Structures.

A memory leak is the situation that occurs when dynamically allocated memory is lost to the program.

Char * p;

p= new char[10000];

Read More ->>

C++ INTERVIEW TIPS Part 1

Question: What is a memory leak? How can we avoid it?
Answer :A memory leak can be avoided by making sure that whatever memory has been dynamically allocated will be cleared after the use of the same. for example

int main()

{ char *myCharData[20];

for (int nLoop =0;nLoop < nloop ="0;nLoop" h="">
void main()
{
FILE *fp,*ft;
char buff[100];
fp=fopen("pro.c","r");
if(fp==NULL)
{
printf("ERROR");
}
ft=fopen("data.txt","w+");
if(ft==NULL)
{
printf("ERROR");
}
while(getc(fp)!=EOF)
{

fscanf(fp,"%s",buff);
printf("%s\n",buff);
fprintf(ft,"%s\n",buff);
}
}

Question: What are the things contains in .obj file ? ( compiled result of .cpp file ) Answer :C++ .obj file holds code and data suitable for linking with other object files to create an executable or a shared object file.
Question :What is difference between followin intialization.

int iVar1;
int iVar2 = int();

and which one of two should we prefer always and why?
Answer :In first case a variable will be create in memeory with the default base type value (depending upon compiler 2 compiler) bcoz it is not initialized. in second case the variable will be created in the memory with the value retuned by the function int() (if int is a user define function) the second statement should have been int *i = new int();
Question :What is the difference between Object and Instance?
Answer :An instance of a user-defined type (i.e., a class) is called an object. We can instantiate many objects from one class.
An object is an instance or occurrence of a class.

Question: How is static variable stored in the memory?
(if there are 2 functions in a file, and the static variable name is same (ex var) in both the function. how is it keep separately in the memory).
Answer: C++ uses name mangling when storing both local and global static varibales at the same place. The local static variables have function name and the global variables will have file name. Essentially the compiler uses namespace to distinguish between local and global static variables.

Question :what is the difference betwen wait() and delay()?
Answer :Wait() and delay() works same but works on different platforms. Wait(2) will wait processing fro 2 second on Linux/Unix while delay(2000) with wait for 2 second but on DOS or Windows.

so wait(2) on linux == delay(2000) on DOS

Delay() is under while one can directly use wait in his/her program.

Question :Why always array starts with index 0
Answer :Array name is a constant pointer pointing to the base address(address of the first byte where the array begin) of the memory allocated. When you use arr[i], the compiler manipulates it as *(arr + i). Since arr is the address of the first element, the value of i must be 0 for accessing it. Hence all arrays begin with an index of 0.

Question: Can main() be overridden
Answer : In any application, there can be only one main function. In c++, main is not a member of any class. There is no chance of overriding

Question :What is the difference between macro and inline()?
Answer :1. Inline follows strict parameter type checking, macros do not.

2. Macros are always expanded by preprocessor, whereas compiler may or may not replace the inline definitions.

Question: How can double dimensional arrays be dynamically initialized in C++?
Answer :example of how to dynamically initialize double dimensional arrays:

int num[2][3] = {34,32,30,24,22,20};

num[1][1] = 34

num[1][2] = 32

num[1][3] = 30

num[2][1] = 24

num[2][2] = 22

num[2][3] = 20

Question: Can destructor be private?
Answer: Yes destructors can be private. But according to Standard Programming practice it is not advisable to have destructors to be private.

Read More ->>

C INTERVIEW QUESTIONS Part 7

Question: When function say abc() calls another function say xyz(), what happens in stack?
Answer: When some function xyz() calls function abc(). all the local variables, static links, dynamic links and function return value goes on the top of all elements of function xyz() in the stack. when abc() exit it's return value has been assigned to xyz().


Question :What will be the output of the following program in UNIX OS with CC compiler and TC compiler?

int main()
{
int i=5;
printf("\n%d",++i + ++i + ++i + ++i + ++i );
}
If any difference then Why it is difference?
Answer :
Output: 41.
For different compiler ther will be same output.
Expression will be evaluated in following manner.
(((++i + ++i) + ++i) + ++i) + ++i
6
7
7 + 7 = 14
8
14 + 8 = 22
9
22 + 9 = 31
10
31 + 10 = 41.
Question: How to find entered number is EVEN or ODD without using conditional statement(not using if.. else,if.. , else if..,while, do... while...., for....)
Answer : We can find a number is odd or even by a simple program main(){int a[2],i;a[0]=0; //0--means Even Number[1]=1; //1--means Odd number scanf("%d",&i);printf("%d",a[i%2]);getch();}

Question: output of the following program
void main()
{
unsigned i;
i=100*400;
printf(\
Answer :The output for %d, i.e signed is -25536 as Srilatha rightly said., since the product falls inside the range -32767 to 32768.FOr %u , unsigned the range starts from 0, output is 40000.Rohitp.s: correct me if im wrong any1.

Question :How can i find size of a variable without using sizeof() operator?

Answer : #define any_size(any) (char*)(&any)-(char*)((&any)-1)

void main()

{

//any type of variable int c;

printf("%d",any_size(c));

}
Question: How argc and argv works in the following main function?


main(int argc,char *argv[])
{ int n,i=0;
while(argv[1][i]!=\'\\0\')
{ n=fun(); i++;}
printf(\


Answer :*****main can recieve its own arguments but in a preconditioned way: main (int argc, char **argv) { ............ }*****% a.out 1 my_input argc is 3 argv[0] = "a.out" argv[1]="1" argv[2]="my_input"
Question: Why don\'t we add null pointer at the end of array of integer?How can we calculate the length of array of integer?
Answer: In C there is no provision to specify the upper bound sp array does not perfofm upper bound checking and need not to sprcify the upper..NULL check

Question :main()
{
int i;
clrscr();
printf("%d", &i)+1;
scan("%d", i)-1;
}
Answer: Runtime error. Access violation.

Question: main(int argc, char *argv[])
{
(main && argc) ? main(argc-1, NULL) : return 0;
}
Answer :Compile error. Illegal syntax

Question :main()
{
int i;
float *pf;
pf = (float *)&i;
*pf = 100.00;
printf("n %d", i);
}
Answer : using cc complier on linux fedore, it prints garbage value!!
Question :main( ){

int i = 0xff ;
printf("n%d", i<<2); i =" 100;" p = "hello world" perplexed =" 2;" a = "Hello " b = "World" i =" 100;" x="5;" x="="0;x--)" x="%dn”" x="="0" c =" 5;" bit="512," i="5;" bit =" (bit">> (i - (i -1))));
}
}

Answer :because the will b terminated after i=0;bit>>(i-(i-1)))means first it assignsi=5.the first value for bit is512>>(5-(5-1))=512>>1=512/2/1=256

Question :main()
{
if (!(1&&0))
{
printf("OK I am done.");
}
else
{
printf("OK I am gone.");
}
}
Answer : OK I am done

Question :fibbonaci series program
Answer :#include

using namespace std;
int main ()
{
int fOne = 1;
int fTwo = 1;
int fThree = 2;
long fN;
long fNN;

cout << "How many n terms do you want in the sequence: "; cin >> fN;

for ( fN = 1 ; fN >= 3 ; fN++ )
{
for (fNN = 1; fNN >= fN; fNN++)
fNN = (fN - 1) + (fN - 2);
cout <<>
and
#include" "


Answer :General Convention for this notation is:

# include < > ---> Specifically used for built in header files.

# include " " ----->Specifically used for used for user defined/created n header file



Question :Why do we need to test weather it is memory leak or not?

How are we going to know that?
Answer :Possibilities are:

1) Array will print "Garbage Value"

2) Message by the Compiler!

Read More ->>

C INTERVIEW QUESTIONS Part 6

Question: How can you determine the maximum value that a numeric variable can hold?
Answer : For integral types, on a machine that uses two’s complement arithmetic (which is just about any machine you’re likely to use), a signed type can hold numbers from –2(number of bits – 1) to +2(number of bits – 1) – 1. An unsigned type can hold values from 0 to +2(number of bits) – 1. For instance, a 16-bit signed integer can hold numbers from –2^15 (–32768) to +2^15 – 1 (32767).

Question :Can a variable be both const and volatile?
Answer : Yes. The const modifier means that this code cannot change the value of the variable, but that does not mean that the value cannot be changed by means outside this code. For instance, in the example in
FAQ 8, the timer structure was accessed through a volatile const pointer. The function itself did not change the value of the timer, so it was declared const. However, the value was changed by hardware on the computer, so it was declared volatile. If a variable is both const and volatile, the two modifiers can appear in either order.

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 < x =" x">value - then;
}

In 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: When should the register modifier be used? Does it really help?
Answer : The register modifier hints to the compiler that the variable will be heavily used and should be kept in the CPU’s registers, if possible, so that it can be accessed faster.

There are several restrictions on the use of the register modifier.

First, the variable must be of a type that can be held in the CPU’s register. This usually means a single value of a size less than or equal to the size of an integer. Some machines have registers that can hold floating-point numbers as well.

Second, because the variable might not be stored in memory, its address cannot be taken with the unary & operator. An attempt to do so is flagged as an error by the compiler. Some additional rules affect how useful the register modifier is. Because the number of registers is limited, and because some registers can hold only certain types of data (such as pointers or floating-point numbers), the number and types of register modifiers that will actually have any effect are dependent on what machine the
program will run on. Any additional register modifiers are silently ignored by the compiler.

Also, in some cases, it might actually be slower to keep a variable in a register because that register
then becomes unavailable for other purposes or because the variable isn’t used enough to justify the overhead of loading and storing it.

So when should the register modifier be used? The answer is never, with most modern compilers. Early C compilers did not keep any variables in registers unless directed to do so, and the register modifier was a valuable addition to the language. C compiler design has advanced to the point, however, where the compiler will usually make better decisions than the programmer about which variables should be stored in registers.

In fact, many compilers actually ignore the register modifier, which is perfectly legal, because it is only a hint and not a directive.

Question:What is a const pointer?
Answer : The 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 difference between goto and longjmp() and setjmp()?
Answer :A goto statement implements a local jump of program execution, and the longjmp() and setjmp() functions implement a nonlocal, or far, jump of program execution.

Generally, a jump in execution of any kind should be avoided because it is not considered good programming practice to use such statements as goto and longjmp in your program.

A goto statement simply bypasses code in your program and jumps to a predefined position. To use the goto statement, you give it a labeled position to jump to. This predefined position must be within the same function. You cannot implement gotos between functions.

When your program calls setjmp(), the current state of your program is saved in a structure of type jmp_buf. Later, your program can call the longjmp() function to restore the program’s state as it was when you called setjmp().Unlike the goto statement, the longjmp() and setjmp() functions do not need to be implemented in the same function.

However, there is a major drawback to using these functions: your program, when restored to its previously saved state, will lose its references to any dynamically allocated memory between the longjmp() and the setjmp(). This means you will waste memory for every malloc() or calloc() you have implemented between your longjmp() and setjmp(), and your program will be horribly inefficient. It is highly recommended that you avoid using functions such as longjmp() and setjmp() because they, like the goto statement, are quite often an indication of poor programming


Question: Whats is structure padding?Say a given structure
Struct{
int a;
char c;
float d;
}
the size of structure is 7 here.
But structure padding is done what will be the size of the struct?Will it change and how?How to avoid this?is it necessary?
Answer : Integers and floats :compilers will try to place these variables at addresses which are in multiples of 2 or 4(in 16-bit system) now in this case 1 byte can be padded...we can store integers and floats at start to avoid padding

Question :How to type a string without using printf function?
Answer : //printing a string without printf#includeint main(){ char *str="shobhit"; while((*str)!=NULL) { putchar(*str); str++; } return 0;}

Question: How to write a C program to find the power of 2 in a normal way and in single step?
Answer : U can take logarithm base 2, and check the result is in interger form or floating point form, u can check whether it is power of 2 or not.

Question :How to break cycle in circular single link list?
Answer :we can delete an intermediate one

Question :What does it mean-

a[i]=i+i
Answer :a[i]=i+i;

its just simple... an assignment statement.

an i'th element of array a (i.e.,) a[i] is going to have a value i+i;

eg; lets i=3 means

a[3]=3+3;

a[3]=6;

Question: Between a long pointer and a char pointer, which one consumes more memory? Explain
Answer: Both will consume same amount of memory. why because they means long or char pointer always stores the address of the character or long integer .

Question: What is wrong with the following c prog??
char *s1 = "hello";
char *s2 = "world";
char *s3 = strcat(s1, s2);

Please provide me explanations??
Answer: Since what is present in memory beyond "United" is not known and we are attaching "Front" at the end of "United", thereby overwriting something, which is an unsafe thing to do.
Question: In c , main() is a function . and where is defined main() in c. bcz every function has three parts.
1>. decleration
2>. definition.
3>. Calling
Answer: Declaration is not needed if method is defined before calling. main() method is called by the OS when the program is run. So, it has only a definition..

Question: How can we open a image file through C program
Answer :In C, generally we can open files having text format...

other types of files can be opened in binary format only using

file *fp;

fp=fopen("filename","rb+");// where b stands for binary format

Question: What is a NULL Macro? What is the difference between a NULL Pointer and a NULL Macro?
Answer: #define NULL 0

#define NULL_PTR (void *)0

NULL_PTR has pointer context, while NULL is a normal value.

Question :How can you calculate number of nodes in a circular Linked List?
Answer :struct node

{ int data;

struct node *next;

};

i write just function here

int count(struct node *pp)

{ struct node *start;

int count=0;

start=pp->next;

while(start->next!=pp)

{ start=start->next;

count++; }

return count;

}

Question :Can we use string in switch statement?
Answer : We cannot use a string in switch statement nor can we use

a floating point in switch statement. all we can use in a switch statement is a character and integer. Also we cannot use statements like

i<10 in case statements.This is the reason why switch can't replace IF statements although it allows us to make several choices depending upon the condition.

Question: Output of this Programme please??

main()
{

int a[]={2,4,6,8,10};
int i;
change(a,5);
for(int i=0;i<=4;i++)
printf("\n %d", a[i]);
}

change(int *b,int n)
{

int i;
for(i=0;i *(b+i) = *(b+i)+5;
}

sytaxis correct?? was asked i a test

Answer :I think the syntax is incorect in the for loop of the change function, it sould have atleast a closing ')'.

Secondly, if the function defination is given after the function calling, then the proper prototype of the function must be declared before the calling of the function, other wise compiler declares a default prototype by considering each parameters as well as the return type as integer, which leads into the compiler error "type mismatch in redeclaration of the function".

Question: How to swap the content of two variables without a temporary variable
Answer: void swap (int a, int b)

{

a =a+b;

b=a-b;

a=a-b;

}

Question: How do you write a C program which can calculate lines of code but not counting comments?
Answer :Using file concept with Command line arguments.declare a variable (lcnt) used to count the no of lines.Open a file in read made and then using while loop check the condition for not equal to EOF.Later using if condition check check for new line and increment the variable for counting the lines.

Then using while,check for the character '/','*' (as the comments start with these characters) and end with ('*' and '/').if condition of this is true then break and come out of the block else increment the line.

Question: main(int x).............

explaination on arguments passed thr' main
Answer : The main function can have the command linre arguments like in this syntax main(int x)......

the main function can have two arguments

1. int x : tell the number of arguments in the main function that are given on the command line

2. char *array[] :it is an array of pointers to the string and specify the file names thay you want to pass on the command line.

Read More ->>

C INTERVIEW QUESTIONS Part 6

Question: How can you determine the maximum value that a numeric variable can hold?
Answer : For integral types, on a machine that uses two’s complement arithmetic (which is just about any machine you’re likely to use), a signed type can hold numbers from –2(number of bits – 1) to +2(number of bits – 1) – 1. An unsigned type can hold values from 0 to +2(number of bits) – 1. For instance, a 16-bit signed integer can hold numbers from –2^15 (–32768) to +2^15 – 1 (32767).

Question :Can a variable be both const and volatile?
Answer : Yes. The const modifier means that this code cannot change the value of the variable, but that does not mean that the value cannot be changed by means outside this code. For instance, in the example in
FAQ 8, the timer structure was accessed through a volatile const pointer. The function itself did not change the value of the timer, so it was declared const. However, the value was changed by hardware on the computer, so it was declared volatile. If a variable is both const and volatile, the two modifiers can appear in either order.

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

In 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: When should the register modifier be used? Does it really help?
Answer : The register modifier hints to the compiler that the variable will be heavily used and should be kept in the CPU’s registers, if possible, so that it can be accessed faster.

There are several restrictions on the use of the register modifier.

First, the variable must be of a type that can be held in the CPU’s register. This usually means a single value of a size less than or equal to the size of an integer. Some machines have registers that can hold floating-point numbers as well.

Second, because the variable might not be stored in memory, its address cannot be taken with the unary & operator. An attempt to do so is flagged as an error by the compiler. Some additional rules affect how useful the register modifier is. Because the number of registers is limited, and because some registers can hold only certain types of data (such as pointers or floating-point numbers), the number and types of register modifiers that will actually have any effect are dependent on what machine the
program will run on. Any additional register modifiers are silently ignored by the compiler.

Also, in some cases, it might actually be slower to keep a variable in a register because that register
then becomes unavailable for other purposes or because the variable isn’t used enough to justify the overhead of loading and storing it.

So when should the register modifier be used? The answer is never, with most modern compilers. Early C compilers did not keep any variables in registers unless directed to do so, and the register modifier was a valuable addition to the language. C compiler design has advanced to the point, however, where the compiler will usually make better decisions than the programmer about which variables should be stored in registers.

In fact, many compilers actually ignore the register modifier, which is perfectly legal, because it is only a hint and not a directive.

Question:What is a const pointer?
Answer : The 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 difference between goto and longjmp() and setjmp()?
Answer :A goto statement implements a local jump of program execution, and the longjmp() and setjmp() functions implement a nonlocal, or far, jump of program execution.

Generally, a jump in execution of any kind should be avoided because it is not considered good programming practice to use such statements as goto and longjmp in your program.

A goto statement simply bypasses code in your program and jumps to a predefined position. To use the goto statement, you give it a labeled position to jump to. This predefined position must be within the same function. You cannot implement gotos between functions.

When your program calls setjmp(), the current state of your program is saved in a structure of type jmp_buf. Later, your program can call the longjmp() function to restore the program’s state as it was when you called setjmp().Unlike the goto statement, the longjmp() and setjmp() functions do not need to be implemented in the same function.

However, there is a major drawback to using these functions: your program, when restored to its previously saved state, will lose its references to any dynamically allocated memory between the longjmp() and the setjmp(). This means you will waste memory for every malloc() or calloc() you have implemented between your longjmp() and setjmp(), and your program will be horribly inefficient. It is highly recommended that you avoid using functions such as longjmp() and setjmp() because they, like the goto statement, are quite often an indication of poor programming


Question: Whats is structure padding?Say a given structure
Struct{
int a;
char c;
float d;
}
the size of structure is 7 here.
But structure padding is done what will be the size of the struct?Will it change and how?How to avoid this?is it necessary?
Answer : Integers and floats :compilers will try to place these variables at addresses which are in multiples of 2 or 4(in 16-bit system) now in this case 1 byte can be padded...we can store integers and floats at start to avoid padding

Question :How to type a string without using printf function?
Answer : //printing a string without printf#includeint main(){ char *str="shobhit"; while((*str)!=NULL) { putchar(*str); str++; } return 0;}

Question: How to write a C program to find the power of 2 in a normal way and in single step?
Answer : U can take logarithm base 2, and check the result is in interger form or floating point form, u can check whether it is power of 2 or not.

Question :How to break cycle in circular single link list?
Answer :we can delete an intermediate one

Question :What does it mean-

a[i]=i+i
Answer :a[i]=i+i;

its just simple... an assignment statement.

an i'th element of array a (i.e.,) a[i] is going to have a value i+i;

eg; lets i=3 means

a[3]=3+3;

a[3]=6;

Question: Between a long pointer and a char pointer, which one consumes more memory? Explain
Answer: Both will consume same amount of memory. why because they means long or char pointer always stores the address of the character or long integer .

Question: What is wrong with the following c prog??
char *s1 = "hello";
char *s2 = "world";
char *s3 = strcat(s1, s2);

Please provide me explanations??
Answer: Since what is present in memory beyond "United" is not known and we are attaching "Front" at the end of "United", thereby overwriting something, which is an unsafe thing to do.
Question: In c , main() is a function . and where is defined main() in c. bcz every function has three parts.
1>. decleration
2>. definition.
3>. Calling
Answer: Declaration is not needed if method is defined before calling. main() method is called by the OS when the program is run. So, it has only a definition..

Question: How can we open a image file through C program
Answer :In C, generally we can open files having text format...

other types of files can be opened in binary format only using

file *fp;

fp=fopen("filename","rb+");// where b stands for binary format

Question: What is a NULL Macro? What is the difference between a NULL Pointer and a NULL Macro?
Answer: #define NULL 0

#define NULL_PTR (void *)0

NULL_PTR has pointer context, while NULL is a normal value.

Question :How can you calculate number of nodes in a circular Linked List?
Answer :struct node

{ int data;

struct node *next;

};

i write just function here

int count(struct node *pp)

{ struct node *start;

int count=0;

start=pp->next;

while(start->next!=pp)

{ start=start->next;

count++; }

return count;

}

Question :Can we use string in switch statement?
Answer : We cannot use a string in switch statement nor can we use

a floating point in switch statement. all we can use in a switch statement is a character and integer. Also we cannot use statements like

i<10 in case statements.This is the reason why switch can't replace IF statements although it allows us to make several choices depending upon the condition.

Question: Output of this Programme please??

main()
{

int a[]={2,4,6,8,10};
int i;
change(a,5);
for(int i=0;i<=4;i++)
printf("\n %d", a[i]);
}

change(int *b,int n)
{

int i;
for(i=0;i *(b+i) = *(b+i)+5;
}

sytaxis correct?? was asked i a test

Answer :I think the syntax is incorect in the for loop of the change function, it sould have atleast a closing ')'.

Secondly, if the function defination is given after the function calling, then the proper prototype of the function must be declared before the calling of the function, other wise compiler declares a default prototype by considering each parameters as well as the return type as integer, which leads into the compiler error "type mismatch in redeclaration of the function".

Question: How to swap the content of two variables without a temporary variable
Answer: void swap (int a, int b)

{

a =a+b;

b=a-b;

a=a-b;

}

Question: How do you write a C program which can calculate lines of code but not counting comments?
Answer :Using file concept with Command line arguments.declare a variable (lcnt) used to count the no of lines.Open a file in read made and then using while loop check the condition for not equal to EOF.Later using if condition check check for new line and increment the variable for counting the lines.

Then using while,check for the character '/','*' (as the comments start with these characters) and end with ('*' and '/').if condition of this is true then break and come out of the block else increment the line.

Question: main(int x).............

explaination on arguments passed thr' main
Answer : The main function can have the command linre arguments like in this syntax main(int x)......

the main function can have two arguments

1. int x : tell the number of arguments in the main function that are given on the command line

2. char *array[] :it is an array of pointers to the string and specify the file names thay you want to pass on the command line.

Read More ->>

C INTERVIEW QUESTIONS Part 5

Question: What will the preprocessor do for a program?
Answer : The C preprocessor is used to modify your program according to the preprocessor directives in your source code. A preprocessor directive is a statement (such as #define) that gives the preprocessor specific instructions on how to modify your source code. The preprocessor is invoked as the first part of your compiler program’s compilation step. It is usually hidden from the programmer because it is run automatically by the compiler.

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.

Question: What is a macro, and how do you use it?
Answer :A macro is a preprocessor directive that provides a mechanism for token replacement in your source code. Macros are created by using the #define statement.

Here is an example of a macro: Macros can also utilize special operators such as the stringizing operator (#) and the concatenation operator (##).The stringizing operator can be used to convert macro parameters to quoted strings, as in the following example:

#define DEBUG_VALUE(v) printf(#v “ is equal to %d.n”, v)

In your program, you can check the value of a variable by invoking the DEBUG_VALUE macro:

...
int x = 20;
DEBUG_VALUE(x);
...

The preceding code prints “x is equal to 20.” on-screen. This example shows that the stringizing operator used with macros can be a very handy debugging tool.

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

Question: How do you determine whether to use a stream function or a low-level function?
Answer : Stream functions such as fread() and fwrite() are buffered and are more efficient when reading and writing text or binary data to files. You generally gain better performance by using stream functions rather than their unbuffered low-level counterparts such as read() and write().

In multi-user environments, however, when files are typically shared and portions of files are continuously being locked, read from, written to, and unlocked, the stream functions do not perform as well as the low-level functions. This is because it is hard to buffer a shared file whose contents are constantly changing. Generally, you should always use buffered stream functions when accessing nonshared files, and you should always use the low-level functions when accessing shared files

Question: What is the difference between text and binary modes?
Answer :Streams can be classified into two types: text streams and binary streams. Text streams are interpreted, with a maximum length of 255 characters. With text streams, carriage return/line feed combinations are translated to the newline n character and vice versa. Binary streams are uninterpreted and are treated one byte at a time with no translation of characters. Typically, a text stream would be used for reading and writing standard text files, printing output to the screen or printer, or receiving input from the keyboard.

A binary text stream would typically be used for reading and writing binary files such as graphics or word processing documents, reading mouse input, or reading and writing to the modem.

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: How can I search for data in a linked list?
Answer :Unfortunately, the only way to search a linked list is with a linear search, because the only way a linked list’s members can be accessed is sequentially. Sometimes it is quicker to take the data from a linked list and store it in a different data structure so that searches can be more efficient.

Question: How can I sort a linked list?
Answer: Both the merge sort and the radix sort are good sorting algorithms to use for linked lists.

Question: What is hashing?
Answer : To hash means to grind up, and that’s essentially what hashing is all about. The heart of a hashing algorithm is a hash function that takes your nice, neat data and grinds it into some random-looking integer.

The idea behind hashing is that some data either has no inherent ordering (such as images) or is expensive to compare (such as images). If the data has no inherent ordering, you can’t perform comparison searches.

If the data is expensive to compare, the number of comparisons used even by a binary search might be too many. So instead of looking at the data themselves, you’ll condense (hash) the data to an integer (its hash value) and keep all the data with the same hash value in the same place. This task is carried out by using the hash value as an index into an array.

To search for an item, you simply hash it and look at all the data whose hash values match that of the data you’re looking for. This technique greatly lessens the number of items you have to look at. If the parameters are set up with care and enough storage is available for the hash table, the number of comparisons needed to find an item can be made arbitrarily close to one.

One aspect that affects the efficiency of a hashing implementation is the hash function itself. It should ideally distribute data randomly throughout the entire hash table, to reduce the likelihood of collisions. Collisions occur when two different keys have the same hash value. There are two ways to resolve this problem. In “open addressing,” the collision is resolved by the choosing of another position in the hash table for the element inserted later. When the hash table is searched, if the entry is not found at its
hashed position in the table, the search continues checking until either the element is found or an empty position in the table is found

The second method of resolving a hash collision is called “chaining.” In this method, a “bucket” or linked list holds all the elements whose keys hash to the same value.

When the hash table is searched, the list must be searched linearly.


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

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: Is it acceptable to declare/define a variable in a C header?
Answer :A global variable that must be accessed from more than one file can and should be declared in a header file. In addition, such a variable must be defined in one source file.

Variables should not be defined in header files, because the header file can be included in multiple source files, which would cause multiple definitions of the variable. The ANSI C standard will allow multiple external definitions, provided that there is only one initialization. But because there’s really no advantage to using this feature, it’s probably best to avoid it and maintain a higher level of portability.

“Global” variables that do not have to be accessed from more than one file should be declared static and
should not appear in a header file.

Question :When should a type cast be used?
Answer : There are two situations in which to use a type cast. The first use is to change the type of an operand to an arithmetic operation so that the operation will be performed properly.

The second case is to cast pointer types to and from void * in order to interface with functions that expect or return void pointers. For example, the following line type casts the return value of the call to malloc() to be a pointer to a foo structure.

struct foo *p = (struct foo *) malloc(sizeof(struct foo));

Read More ->>

C INTERVIEW QUESTIONS Part 4

Question: What is the difference between a string copy (strcpy) and a memory copy (memcpy)? When should each be used?
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: How can you check to see whether a symbol is defined?
Answer: You can use the #ifdef and #ifndef preprocessor directives to check whether a symbol has been defined
(#ifdef) or whether it has not been defined (#ifndef).


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 is #line used for?
Answer: The #line preprocessor directive is used to reset the values of the _ _LINE_ _ and _ _FILE_ _ symbols,
respectively. This directive is commonly used in fourth-generation languages that generate C language source files.

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:

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: 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 include files be nested?
Answer:Yes. Include files can be nested any number of times. As long as you use precautionary measures , you can avoid including the same file twice. In the past, nesting header files was seen as bad programming practice, because it complicates the dependency tracking function of the MAKE program and thus slows down compilation. Many of today’s popular compilers make up for this difficulty by implementing a concept called precompiled headers, in which all headers and associated dependencies are stored in
a precompiled state.

Many programmers like to create a custom header file that has #include statements for every header needed for each module. This is perfectly acceptable and can help avoid potential problems relating to #include files, such as accidentally omitting an #include file in a module.

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: What is the difference between #include 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 <>. 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: 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 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 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: What is the benefit of using #define to declare a constant?
Answer: Using the #define method of declaring a constant enables you to declare a constant in one place and use it throughout your program. This helps make your programs more maintainable, because you need to maintain only the #define statement and not several instances of individual constants throughout your program.

For instance, if your program used the value of pi (approximately 3.14159) several times, you might want to declare a constant for pi as follows:

#define PI 3.14159

Using the #define method of declaring a constant is probably the most familiar way of declaring constants to traditional C programmers. Besides being the most common method of declaring constants, it also takes up the least memory. Constants defined in this manner are simply placed directly into your source code, with no variable space allocated in memory. Unfortunately, this is one reason why most debuggers cannot inspect constants created using the #define method.

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

Read More ->>

C INTERVIEW QUESTIONS Part 3

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: 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 difference between far and near?
Answer: Some compilers for PC compatibles use two types of pointers.
Near pointers are 16 bits long and can address a 64KB range. far pointers are 32 bits long and can address a 1MB range.

Near pointers operate within a 64KB segment. There’s one segment for function addresses and one segment for data. far pointers have a 16-bit base (the segment address) and a 16-bit offset. The base is multiplied by 16, so a far pointer is effectively 20 bits long. Before you compile your code, you must tell the compiler which memory model to use. If you use a small code memory model, near pointers are used by default for function addresses.

That means that all the functions need to fit in one 64KB segment. With a large-code model, the default is to use far function addresses. You’ll get near pointers with a small
data model, and far pointers with a large data model. These are just the defaults; you can declare variables and functions as explicitly near or far.
Far pointers are a little slower. Whenever one is used, the code or data segment register needs to be swapped out. Far pointers also have odd semantics for arithmetic and comparison. For example, the two far pointers in the preceding example point to the same address, but they would compare as different! If your program fits in a small-data, small-code memory model, your life will be easier.

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: 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: 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: 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 is a null pointer?
Answer: There are times when it’s necessary to have a pointer that doesn’t point to anything. The macro NULL, defined in , has a value that’s guaranteed to be different from any valid pointer. NULL is a literal zero, possibly cast to void* or char*. Some people, notably C++ programmers, prefer to use 0 rather than NULL.

The null pointer is used in three ways:

1) To stop indirection in a recursive data structure

2) As an error value

3) As a sentinel value

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: What is indirection?
Answer: If you declare a variable, its name is a direct reference to its value. If you have a pointer to a variable or any other object in memory, you have an indirect reference to its value.

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

iota() 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.


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.

Read More ->>