Friday, February 5, 2010

C INTERVIEW QUESTIONS

1. What is a static function?

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

All function by default Static nature.



2. What is the difference between #include and #include “file”?

A. When writing your C program, you can include files in two ways. The first way is to surround the file you want to include with the angled brackets < and >. This method of inclusion tells the preprocessor to look for the file in the predefined default location.

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.

3. What is the benefit of using an enum rather than a #define constant?

A. 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 to3, 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.



4. Difference between arrays and pointers?

A. Pointers are used to manipulate data using the address. Pointers use * operator to access the data pointed to by them



Arrays use subscripted variables to access and manipulate data. Array variables can be equivalently written using pointer expression.

5. What is the difference between far and near?

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







6. if "condition" printf("Hello"); else printf("World") what should be the condition, so the output will be HelloWorld.

A.

main()

{

If(!printf(“Hello”))

printf(“Hello”);

else

printf(“Worldn”);

}



7. Is it better to use malloc() or calloc()?

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

8. What is the quickest sorting method to use?

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



9. Can we execute printf statement without using semicolan?

A. By using if, for,do while, while loop we execute printf statement without using semicolon.

example shown below...

main()

{

if(printf("hello"))

}

10. Is it possible to execute code even after the program exits the main() function?

A. The standard C library provides a function named atexit() that can be used to perform ?cleanup? operations when your program terminates. You can set up a set of functions you want to perform automatically when your program exits by passing function pointers to the at exit() function.________________________________________

This can be done by using #pragma directive as:

#pragma exit



Using above code, any function can be executed after program exits the main function but function must be declared before pragma directive is reached.





11. When should a far pointer be used?

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

12. Can static variables be declared in a header file?

A. Static variables can be declared in a header file. However, their definition should also be provided in the same header file. But , doing this makes the static variable as a private copy of the header file ie it cannot be used elsewhere. In normal cases, this is not intended from a header file. It is generally a ad idea to use a static variable in a header file.

13. How can I open a file so that other programs can update it at the same time?

A. Your C compiler library contains a low-level file function called sopen() that can be used to open a file in shared mode. Beginning with DOS 3.0, files could be opened in shared mode by loading a special program named SHARE.EXE. Shared mode, as the name implies, allows a file to be shared with other programs as well as your own.



Using this function, you can allow other programs that are running to update the same file you are updating.



The sopen() function takes four parameters: a pointer to the filename you want to open, the operational

mode you want to open the file in, the file sharing mode to use, and, if you are creating a file, the mode to create the file in. The second parameter of the sopen() function, usually referred to as the ?operation flag?parameter, can have the following values assigned to it:





Constant Description O_APPEND Appends all writes to the end of the file



O_BINARY Opens the file in binary (untranslated) mode

O_CREAT If the file does not exist, it is created

O_EXCL If the O_CREAT flag is used and the file exists, returns an error

O_RDONLY Opens the file in read-only mode

O_RDWR Opens the file for reading and writing

O_TEXT Opens the file in text (translated) mode

O_TRUNC Opens an existing file and writes over its contents

O_WRONLY Opens the file in write-only mode



The third parameter of the sopen() function, usually referred to as the ?sharing flag,? can have the following values assigned to it:



Constant Description

SH_COMPAT No other program can access the file

SH_DENYRW No other program can read from or write to the file

SH_DENYWR No other program can write to the file

SH_DENYRD No other program can read from the file

SH_DENYNO Any program can read from or write to the file



If the sopen() function is successful, it returns a non-negative number that is the file?s handle. If an error occurs, ?1 is returned, and the global variable errno is set to one of the following values:



Constant Description

ENOENT File or path not found

EMFILE No more file handles are available

EACCES Permission denied to access file

EINVACC Invalid access code

Constant Description

14. Write the equivalent expression for x%8?

A. x & 7

15. What is the heap?

A. The heap is where malloc(), calloc(), and realloc() get memory.



Getting memory from the heap is much slower than getting it from the stack. On the other hand, the heap is much more flexible than the stack. Memory can be allocated at any time and deallocated in any order. Such memory isn?t deallocated automatically; you have to call free().



Recursive data structures are almost always implemented with memory from the heap. Strings often come from there too, especially strings that could be very long at runtime. If you can keep data in a local variable (and allocate it from the stack), your code will run faster than if you put the data on the heap. Sometimes you can use a better algorithm if you use the heap?faster, or more robust, or more flexible. It?s a tradeoff.



If memory is allocated from the heap, it?s available until the program ends. That?s great if you remember to deallocate it when you?re done. If you forget, it?s a problem. A ?memory leak? is some allocated memory that?s no longer needed but isn?t deallocated. If you have a memory leak inside a loop, you can use up all the memory on the heap and not be able to get any more. (When that happens, the allocation functions return a null pointer.) In some environments, if a program doesn?t deallocate everything it allocated, memory stays unavailable even after the program ends.

16. When should the volatile modifier be used?

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

17. What is the difference between NULL and NUL?

A. NULL is a macro defined in for the null pointer.



NUL is the name of the first character in the ASCII character set. It corresponds to a zero value. There?s no standard macro NUL in C, but some people like to define it.



The digit 0 corresponds to a value of 80, decimal. Don?t confuse the digit 0 with the value of NUL

NULL can be defined as ((void*)0), NUL as ??.

18. Why should I prototype a function?

A. A function prototype tells the compiler what kind of arguments a function is looking to receive and what

kind of return value a function is going to give back. This approach helps the compiler ensure that calls to a function are made correctly and that no erroneous type conversions are taking place.



19. How can you determine the size of an allocated portion of memory?

A. The malloc/free implementation remembers the size of each block as it is allocated, so it is not necessary to remind it of the size when freeing. (Typically, the size is stored adjacent to the allocated block, which is why things usually break badly if the bounds of the allocated block are even slightly overstepped

20. What is hashing?

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

21. What is the purpose of realloc( )?

A. The function realloc(ptr,n) uses two arguments.the first argument ptr is a pointer to a block of memory for which the size is to be altered.The second argument n specifies the

new size.The size may be increased or decreased.If n is greater than the old size and if sufficient space is not available subsequent to the old region, the function realloc( )

may create a new region and all the old data are moved to the new region.



________________________________________



realloc() can be used for re-sizing the allocated memory. No doubt in it. But due to this, some data which is there in that memory may get corrupted. So it is better not to use the realloc function.



I think the following program will help in understanding the point.



#include

int main()

{

int *ptr,*ptr_new;

int num,newsize,i;



printf("

Enter the number of elements in the array");

scanf("%d",&num);

ptr= (int *)malloc( num * sizeof(int) );

if (ptr == NULL)

{

printf("

Cannot allocate memory");

return -1;

}

for(i=0;i
scanf("%d",&ptr[i]);



printf("

The elements entered are ::



");

for(i=0;i
printf("

Address of %d ----> %u",ptr[i],&ptr[i]);



printf("

Enter the new size of the array");

scanf("%d",&newsize);



ptr_new= (int *)realloc(ptr,newsize * sizeof(int));

if (ptr_new == NULL)

{

printf("

Cannot Re-allocate memory");

return -1;

}

for(i=0;i
{

if(i >= num )

{

printf("Enter %d element ",i+1);

scanf("%d",&ptr[i]);

}

}



for(i=0;i
printf("

Address of %d ----> %u",ptr_new[i],&ptr_new[i]);



system("pause");

return 0;

}

22. Can a variable be both const and volatile?

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

23. Can include files be nested?

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

24. How do you override a defined macro?

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

25. What is a pragma?

A. The #pragma preprocessor directive allows each compiler to implement compiler-specific features that can be turned on and off with the #pragma statement. For instance, your compiler might support a feature called loop optimization. This feature can be invoked as a command-line option or as a #pragma directive.



To implement this option using the #pragma directive, you would put the following line into your code:



#pragma loop_opt(on)



Conversely, you can turn off loop optimization by inserting the following line into your code:



#pragma loop_opt(off)







26. What is the purpose of main( ) function?

A. The function main( ) invokes other functions within it.It is the first function to be called when the program starts execution.



It is the starting function



It returns an int value to the environment that called the program



Recursive call is allowed for main( ) also.



It is a user-defined function



Program execution ends when the closing brace of the function main( ) is reached.



It has two arguments 1)argument count and 2) argument vector (represents strings passed).



Any user-defined name can also be used as parameters for main( ) instead of argc and argv

27. How do you print an address?

A. The safest way is to use printf() (or fprintf() or sprintf()) with the %P specification. That prints a void

pointer (void*). Different compilers might print a pointer with different formats. Your compiler will pick

a format that?s right for your environment.



If you have some other kind of pointer (not a void*) and you want to be very safe, cast the pointer to a void*:



printf( ?%Pn?, (void*) buffer );________________________________________

Address can also be printed using %x. Here is a program which gives the same output for both %p (not %P) and %x.

#include

int main()

{

char *ch;

char ch1='b';

ch=&ch1;

printf("%p %x",(void *)ch,(void *)ch);

getch();

}

28. What is a ?null pointer assignment? error? What are bus errors, memory faults, and core dumps?

A. These are all serious errors, symptoms of a wild pointer or subscript.

Null pointer assignment is a message you might get when an MS-DOS program finishes executing. Some

such programs can arrange for a small amount of memory to be available ?where the NULL pointer points to? (so to speak). If the program tries to write to that area, it will overwrite the data put there by the compiler.

When the program is done, code generated by the compiler examines that area. If that data has been changed, the compiler-generated code complains with null pointer assignment.

This message carries only enough information to get you worried. There?s no way to tell, just from a null

pointer assignment message, what part of your program is responsible for the error. Some debuggers, and some compilers, can give you more help in finding the problem.

Bus error: core dumped and Memory fault: core dumped are messages you might see from a program running under UNIX. They?re more programmer friendly. Both mean that a pointer or an array subscript was wildly out of bounds. You can get these messages on a read or on a write. They aren?t restricted to null pointer problems.

The core dumped part of the message is telling you about a file, called core, that has just been written in your current directory. This is a dump of everything on the stack and in the heap at the time the program was running. With the help of a debugger, you can use the core dump to find where the bad pointer was used.

That might not tell you why the pointer was bad, but it?s a step in the right direction. If you don?t have write permission in the current directory, you won?t get a core file, or the core dumped message.

29. What is the easiest sorting method to use?

A. The answer is the standard library function qsort(). It is 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));

30. How can I convert a number to a string?

A.

1. We can convert number to string using built in function itoa().

2. we can convert number to string using sprintf() function as shown below.



char result[100];

int num = 24;

sprintf( result,"%d",num);

31. Are pointers integers?

A. Yes. Pointer is an integer because it stores the address value of other variable. Actually its a subset of integers because it contains only +ve values. But note that all the integers are not pointers.

32. void main()

{

float a= 0.7;

if (a < 0.7)

printf("c");

else

printf("c++");

}

Output of the above program is c. Why? Whereas the same program with 0.8 instead of 0.7 gives c++ as the output? Why explain?

A. this is because of rounding the value of variable a.

i.e.

a=0.7 is rounded to

=0.699999988

and the constant 0.7 is as

=0.69999999999

so a<0.7 ii true so it print "c"

but in case of 0.8

a=0.800000011 and

constant 0.8 is 0.8000000000000000

33. Can you define which header file to include at compile time?

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

34. How can you check to see whether a symbol is defined?

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

35. Why should we assign NULL to the elements (pointer) after freeing them?

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

36. Can math operations be performed on a void pointer?

A. No. Pointer addition and subtraction are based on advancing the pointer by a number of elements. By definition, if you have a void pointer, you don?t know what it?s pointing to, so you don?t know the size of what it?s pointing to. If you want pointer arithmetic to work on raw addresses, use character pointers.

37. When does the compiler not implicitly generate the address of the first element of an array?

A. Whenever an array name appears in an expression such as



- array as an operand of the sizeof operator



- array as an operand of & operator



- array as a string literal initializer for a character array



then the compiler does not implicitly generate the address of the address of the first element of an array.



38. Is using exit() the same as using return?

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

Prototype of atexit() is :

int atexit ( void ( * function ) (void) );



The function pointed by the function pointer argument is called when the program terminates normally.



If more than one atexit function has been specified by different calls to this function, they are all executed in reverse order as a stack, i.e. the last function specified is the first to be executed at exit.



One single function can be registered to be executed at exit more than once.



/* atexit example */

#include

#include



void fnExit1 (void)

{

puts ("Exit function 1.");

}



void fnExit2 (void)

{

puts ("Exit function 2.");

}



int main ()

{

atexit (fnExit1);

atexit (fnExit2);

puts ("Main function.");

return 0;

}



Output:



Main function.

Exit function 2.

Exit function 1.



//Here the output is in reverse order as a stack, i.e. the last function specified is the first to be executed at exit.



39. Write a program with out using main() function?

A. #include

_start()

{

_exit(myFunction());



}



int myFunction()

{

write(1,”Hello World”,12);

}



--------------------------------------------------------------

But you have compile this file as below



gcc -nostartfiles foo.c

40. What is page thrashing?

A. Some operating systems (such as UNIX or Windows in enhanced mode) use virtual memory. Virtual

memory is a technique for making a machine behave as if it had more memory than it really has, by using disk space to simulate RAM (random-access memory). In the 80386 and higher Intel CPU chips, and in most other modern microprocessors (such as the Motorola 68030, Sparc, and Power PC), exists a piece of hardware called the Memory Management Unit, or MMU.



The MMU treats memory as if it were composed of a series of ?pages.? A page of memory is a block of

contiguous bytes of a certain size, usually 4096 or 8192 bytes. The operating system sets up and maintains a table for each running program called the Process Memory Map, or PMM. This is a table of all the pages of memory that program can access and where each is really located.



Every time your program accesses any portion of memory, the address (called a ?virtual address?) is processed by the MMU. The MMU looks in the PMM to find out where the memory is really located (called the ?physical address?). The physical address can be any location in memory or on disk that the operating system has assigned for it. If the location the program wants to access is on disk, the page containing it must be read from disk into memory, and the PMM must be updated to reflect this action (this is called a ?page fault?).



Because accessing the disk is so much slower than accessing RAM, the operating system tries to keep as much of the virtual memory as possible in RAM. If you?re running a large enough program (or several small programs at once), there might not be enough RAM to hold all the memory used by the programs, so some of it must be moved out of RAM and onto disk (this action is called ?paging out?).

The operating system tries to guess which areas of memory aren?t likely to be used for a while (usually based on how the memory has been used in the past). If it guesses wrong, or if your programs are accessing lots of memory in lots of places, many page faults will occur in order to read in the pages that were paged out. Because all of RAM is being used, for each page read in to be accessed, another page must be paged out. This can lead to more page faults, because now a different page of memory has been moved to disk.



The problem of many page faults occurring in a short time, called ?page thrashing,? can drastically cut the performance of a system. Programs that frequently access many widely separated locations in memory are more likely to cause page thrashing on a system. So is running many small programs that all continue to run even when you are not actively using them. To reduce page thrashing, you can run fewer programs simultaneously. Or you can try changing the way a large program works to maximize the capability of the operating system to guess which pages won?t be needed. You can achieve this effect by caching values or changing lookup algorithms in large data structures, or sometimes by changing to a memory allocation library which provides an implementation of malloc() that allocates memory more efficiently. Finally, you might consider adding more RAM to the system to reduce the need to page out.













































































41. Can the sizeof operator be used to tell the size of an array passed to a function?

A. YES.You can tell how large the array is. However, you cannot determine how many elements have been copied into it so far.



EX: Take for instance the following code.



int testList[5];

int sizeofList = sizeof(testList);

printf("sizeof list = %d", sizeofList);



The output will be: "sizeof list = 20"

Meaning that 4(int) * 5 = 20.

42. What is difference between static and global static variable?

A. Local static defines the scope with in the functions; incase of global static will be module level scope.



Both will store in a data segments

A global static variable strictly has internal linkage,that is it is limited to one source file only and cannot be accessed in other files even after using extern keyword.Use it when you want to maintain security and limit your gloal variable to a single file.

Applying static on local variable:

1.The life of the variable is extended between function call,that means the variable still resides in memory,but the scope,that is the accessibility of variable in other functions is limited.Thus a static local variable behaves like a semi-global variable.

2.Cannot be reinitialised,example

int fun(void);

int main()

{

printf("%d",fun());//o/p =11

printf("%d",fun());//o/p = 12

return 0;

}

int fun(void)

{

static int b=10;/*Try removing static and check the result for clarity*/

b++;

return b;

}

43. How are pointer variables initialized?

A. Pointer variable are initialized by one of the following two ways



1. Static memory allocation

2. Dynamic memory allocation

44. Code for swapping of two numbers without using temporary variable using C.

A. 1st method :

a = a + b;

b = a - b;

a = a - b;

2nd method :

a = a xor b;(a^b)

b = b xor a;(b^a)

a = a xor b; (a^b)

45. Is it better to use a pointer to navigate an array of values,or is it better to use a subscripted array name?

A. It’s easier for a C compiler to generate good code for pointers than for subscripts.

46. How I can add two numbers in c language without using Arithmetic operators?

A.

1. c = (a ^ b)|((a&b)<<1);



2. int a = 8, b =20;

int i;

for(i = 0; i < b; i++)

a++;

printf("sum = %dn",a);

47. What is a null pointer?

A. Null pointer is a pointer and it’s doesn’t point to anything.

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

48. When should a type cast be used?

A. 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));

49. What is an lvalue?

A. An lvalue is an expression to which a value can be assigned. The lvalue expression is located on the left side of an assignment statement, whereas an rvalue is located on the right side of an assignment statement. Each assignment statement must have an lvalue and an rvalue. The lvalue expression must reference a storable variable in memory. It cannot be a constant.

50. How to find entered number is EVEN or ODD without using conditional statement (not using if.. else,if.. , else if..,while, do... while...., for....)

A.

main()

{

int num;

char *arr[] = {"EVEN","ODD"};

printf("Enter a Num:");

scanf("%d",&num);

printf("the num is : %sn",arr[num%2]);

}

51. What is the difference between a string copy (strcpy) and a memory copy (memcpy)? When should each be used?

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

52. What is an argument? Differentiate between formal arguments and actual arguments?

A. An argument is an entity used to pass the data from calling function to the called function. Formal arguments are the arguments available in the function definition. They are preceded by their own data types. Actual arguments are available in the function call.

53. Write a program to delete an element from an array?

A.

main()

{

int a[SIZE],del,j,i;

for(i=0;i
{

j=i+1;

printf(" Enter the %d element of array",j);

scanf("%d",&a[i]);

}

printf(" Enter the element to be deleted");

scanf("%d",&del);

del--;

for(i=del;i
a[i]=a[i+1];

a[SIZE-1]=0;

printf(" Element has been deleted");

printf(" Array now is..... ");

for(i=0;i
printf("%d ",a[i]);

}

54. What is the stack?

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

55. Write Addition of two numbers using Bitwise operators.

A. c = (a ^ b)|((a&b)<<1);

56. How many levels of pointers can you have?

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.

57. How can I convert a string to a number?

A. The standard C library provides several functions for converting strings to numbers of all formats (integers, longs, floats, and so on) and vice versa.



The following functions can be used to convert strings to numbers:



Function Name Purpose



atof() Converts a string to a double-precision floating-point value.



atoi() Converts a string to an integer.



atol() Converts a string to a long integer.



strtod() Converts a string to a double-precision floating-point value and reports any ?leftover? numbers that could not be converted.



strtol() Converts a string to a long integer and reports any ?leftover? numbers that could not be converted.



strtoul() Converts a string to an unsigned long integer and reports any ?leftover? numbers that could not be converted.



58. my_atoi implementation: Ensure that this function handles + or -.

A.

main()

{

char *str;

int num;

str = (char *)malloc(sizeof(char));

printf("Enter a String:");

scanf("%s",str);

num = my_atoi(str);

printf("num = %dn",num);

}

int my_atoi(char *str1)

{

int i,sn = 1;

int n =0;

for(i = 0; (str1[i]>='0' && str1[i]<='9')||(str1[i]=='+' || str1[i]=='-'||str1[i]==' ');i++)

{ if(str1[i]=='+' || str1[i]=='-'||str1[i]==' ')

{

sn = (str1[i]=='-')?-1:1;



}

else

{

n = n *10 +(str1[i]-'0');

}

}

return sn * n;

}

59. sum_digits: "12345" to 15

A.

#include

main()

{

char *str = "12345";

int i,sum = 0;

/* for(i = 0; i < strlen(str);i++)

sum = sum +(str[i] - 48);*/

while(*str != '�')

{

sum = sum + (*str-48);

str++;

}

printf("sum = %dn",sum);



}

60. What are the standard predefined macros?

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



61. Is it better to use a macro or a function?

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

62. How do you print only part of a string?

A.

main()

{

char *str;

int i,start,end;

str = (char *)malloc(sizeof(char));

printf("Enter a string:");

scanf("%s",str);

printf("Enter a start and End nos:");

scanf("%d %d",&start,&end);

for(i = start; i <= end; i++)

printf("%c",*(str+i));

printf("n");

}

63. What will the preprocessor do for a program?

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

64. why n++ executes faster than n+1?

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

65. How much memory does a static variable takes?

A. static variable takes the memory of the type.

Static int will occupy size of int

static char will occupy size of char

66. How to print 1 to 100 without using any conditional loop?

A.

main()

{

int i = 100;

print(i);

}

print(int a)

{

printf("%dt",a^1?print(a-1):a);

return a+1;

}

67. Can the size of an array be declared at runtime?

A. No. In an array declaration, the size must be known at compile time. You can’t specify a size that is known only at runtime. For example, if i is a variable, you can?t write code like this:



char array[i]; /* not valid C */



Some languages provide this latitude. C doesn’t. If it did, the stack would be more complicated, function calls would be more expensive, and programs would run a lot slower. If you know that you have an array but you won’t know until runtime how big it will be, declare a pointer to it and use malloc() or calloc() to allocate the array from the heap.

68.

main()

{

printf("%x",-1<<4);

}

A. Depending on the machine implementation it will result in FFFFFF0 (for 32bit ) or FFF0 (16 bit )

69. What is static memory allocation and dynamic memory allocation?

A. Static memory allocation: The compiler allocates the required memory space for a declared variable.By using the address of operator,the reserved address is obtained and this address may be assigned to a pointer variable.Since most of the declared variable have static memory,this way of assigning pointer value to a pointer variable is known as static memory allocation. memory is assigned during compilation time.



Dynamic memory allocation: It uses functions such as malloc( ) or calloc( ) to get memory dynamically.If these functions are used to get memory dynamically and the values returned by these functions are assingned to pointer variables, such assignments are known as dynamic memory allocation.memory is assined during run time.

70. How do you determine whether to use a stream function or a low-level function?

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

71. What is the benefit of using const for declaring constants?

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



72. How can C programs run without header files?

A.

c programming run without header file

write example given below.

void main()

{

clrscr();

printf("hello");

getch();

}

You cannot run a C program without header files. By default some compilers include header files like stdio.h but in the above program, functions getch() and clrscr() use header files which should be mentioned by the programmer. If the above program should run then the programmer should implement the functions inside the code.

73. Differentiate between a linker and linkage?

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

74. How can you avoid including a header more than once?

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

















75.

struct Foo

{

char *pName;

};

main()

{

struct Foo *obj = malloc(sizeof(struct Foo));

strcpy(obj->pName,"yani");

printf("%s", obj->pName);

}

A. As memory is not allocated for pName in structure. Program will crash.

Solution:

struct Foo

{

char *pName;

};

main()

{

struct Foo *obj = malloc(sizeof(struct Foo));

obj->pName = malloc(sizeof(char));

strcpy(obj->pName,"yani");

printf("%s", obj->pName);

free(obj->pName);

free(obj);

}

76. How to find a given number is armstrong number or not in "c".?

A.

given no ,n=153,



n1=n; while(n>=0) {



r=n%10;



sum+=r*r*r;



n=n/10;}



if(n1==sum)then armstrong else not

77. What is the use of Bitwise operators?

A. Bitwise and operator (&) is used to check that a particular bit is ON (1) or OFF (0) or to unset a particular bit and bitwise OR operator is used to set a particular bit of a constant

78. What are the advantages of the functions?

A.

-Debugging is easier



-It is easier to understand the logic involved in the program



-Testing is easier



-Recursive call is possible



-Irrelevant details in the user point of view are hidden in functions



-Functions are helpful in generalizing the program

79.Diffenentiate between an internal static and external static variable?

A. An internal static variable is declared inside a block with static storage class whereas an external static variable is declared outside all the blocks in a file.An internal static variable has persistent storage,block scope and no linkage.An external static variable has permanent storage,file scope and internal linkage.

80. What is the benefit of using #define to declare a constant?

A.

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.

No comments:

Post a Comment