Thursday, March 4, 2010
1. What is C language ?
a. The C programming language is a standardized programming language developed in the early 1970s by Ken Thompson and Dennis Ritchie for use on the UNIX operating system. It has since spread to many other operating systems, and is one of the most widely used programming languages. C is prized for its efficiency, and is the most popular programming language for writing system software, though it is also used for writing applications.
2. What does static variable mean?
3. #include |
4. value of y 0 z 10 After first call 5. value of y 10 z 10 After second call 6. value of y 20 z 10 After third call |
7. What are the different storage classes in C ?
8. What is hashing ?
9. Can static variables be declared in a header file ?
a. 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.
10. Can a variable be both constant 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.
b. 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.
11. 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.
b. 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.
12. What is a null pointer ?
a. 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*.
b. Some people, notably C++ programmers, prefer to use 0 rather than NULL.
c. The null pointer is used in three ways:
13. What is the output of printf("%d") ?
1. When we write printf("%d",x); this means compiler will print the value of x. But as here, there is nothing after %d so compiler will show in output window garbage value.
2. When we use %d the compiler internally uses it to access the argument in the stack (argument stack). Ideally compiler determines the offset of the data variable depending on the format specification string. Now when we write printf("%d",a) then compiler first accesses the top most element in the argument stack of the printf which is %d and depending on the format string it calculated to offset to the actual data variable in the memory which is to be printed. Now when only %d will be present in the printf then compiler will calculate the correct offset (which will be the offset to access the integer variable) but as the actual data object is to be printed is not present at that memory location so it will print what ever will be the contents of that memory location.
3. Some compilers check the format string and will generate an error without the proper number and type of arguments for things like printf(...) and scanf(...).
malloc()
14. What is the difference between calloc() and malloc() ?
1. calloc(...) allocates a block of memory for an array of elements of a certain size. By default the block is initialized to 0. The total number of memory allocated will be (number_of_elements * size).
a. malloc(...) takes in only a single argument which is the memory required in bytes. malloc(...) allocated bytes of memory and not blocks of memory like calloc(...).
2. malloc(...) allocates memory blocks and returns a void pointer to the allocated space, or NULL if there is insufficient memory available.
b. calloc(...) allocates an array in memory with elements initialized to 0 and returns a pointer to the allocated space. calloc(...) calls malloc(...) in order to use the C++ _set_new_mode function to set the new handler mode.
15. What is the difference between printf() and sprintf() ?
a. sprintf() writes data to the character array whereas printf(...) writes data to the standard output device.
16. How to reduce a final size of executable ?
a. Size of the final executable can be reduced using dynamic linking for libraries.
17. Can you tell me how to check whether a linked list is circular ?
18. Advantages of a macro over a function ?
19. What is the difference between strings and character arrays ?
20. Write down the equivalent pointer expression for referring the same element a[i][j][k][l] ?
21. Which bit wise operator is suitable for checking whether a particular bit is on or off ?
a. The bitwise AND operator. Here is an example:
22. Which bit wise operator is suitable for turning off a particular bit in a number ?
a.
The bitwise AND operator, again. In the following code snippet, the bit number 24 is reset to zero.
b. some_int = some_int & ~KBit24;
23. Which bit wise operator is suitable for putting on a particular bit in a number ?
a. The bitwise OR operator. In the following code snippet, the bit number 24 is turned ON:
b. some_int = some_int | KBit24;
24. Does there exist any other function which can be used to convert an integer or a float to a string ?
a. Some implementations provide a nonstandard function called itoa(), which converts an integer to string.
25. Why does malloc(0) return valid memory address ? What's the use ?
26. Difference between const char* p and char const* p
a. In const char* p, the character pointed by ‘p’ is constant, so u cant change the value of character pointed by p but u can make ‘p’ refer to some other location.in char const* p, the ptr ‘p’ is constant not the character referenced by it, so u cant make ‘p’ to reference to any other location but u can change the value of the char pointed by ‘p’.
27. What is the result of using Option Explicit ?
28. What is the benefit of using an enum rather than a #define constant ?
29. What is the quickest sorting method to use ?
30. 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).
d. 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.
31. When should the register modifier be used? Does it really help?
a. 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.
b. 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.
c. 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.
d. 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.
e. 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.
f. 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.
g. In fact, many compilers actually ignore the register modifier, which is perfectly legal, because it is only a hint and not a directive.
32. How can you determine the size of an allocated portion of memory ?
a. You can’t, really. free() can , but there’s no way for your program to know the trick free() uses. Even if you disassemble the library and discover the trick, there’s no guarantee the trick won’t change with the next release of the compiler
33. 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).
b. 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.
c. 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.
d. 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).
e. 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).
f. 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.
g. 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.
h. 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.
34. 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
b. array as an operand of the sizeof operator
c. array as an operand of & operator
d. array as a string literal initializer for a character array
e. Then the compiler does not implicitly generate the address of the address of the first element of an array.
35. 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.
b. 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:
c. #define PI 3.14159
d. 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.
e. 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.
36. How can I search for data in a linked list ?
a. 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.
b. 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.
37. 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.
b. 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.
c. 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.
38. 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).
b. If the program tries to write to that area, it will overwrite the data put there by the compiler.
c. 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.
d. 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.
e. 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.
f. 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.
g. 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
39. 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.
b. The second case is to cast pointer types to and from void * in order to interface with functions that expect or return void pointers.
c. For example, the following line type casts the return value of the call to malloc() to be a pointer to a foo structure.
d. struct foo *p = (struct foo *) malloc(sizeof(struct foo));
40. 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.
b. 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.
41. 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.
b. The following functions can be used to convert strings to numbers:
Function Name Purpose
c. 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.
42. How can I convert a number to a string ?
a. The standard C library provides several functions for converting numbers of all formats (integers, longs, floats, and so on) to strings and vice versa
43. 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.
b. 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.
44. What is the stack ?
a. 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.
b. 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.
c. 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.
d. 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.
45. 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.
b. 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*:
c. printf( %Pn, (void*) buffer );
46. Can a file other than a .h file be included with #include ?
a. The preprocessor will include whatever file you specify in your #include statement. Therefore, if you have the line
b. #include
c. 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.
d. 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.
e. 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.
f. 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.
47. What is Preprocessor ?
a. The preprocessor is used to modify your program according to the preprocessor directives in your source code.
b. Preprocessor directives (such as #define) give the preprocessor specific instructions on how to modify your source code. The preprocessor reads in all of your include files and the source code you are compiling and creates a preprocessed version of your source code.
c. 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.
d. The preprocessor contains many features that are powerful to use, such as creating macros, performing conditional compilation, inserting predefined environment variables into your code, and turning compiler features on and off.
e. For the professional programmer, in-depth knowledge of the features of the preprocessor can be one of the keys to creating fast, efficient programs.
48. How can you restore a redirected standard stream ?
a. 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?
b. By using the standard C library functions named dup() and fdopen(), you can restore a standard stream such as stdout to its original state.
c. The dup() function duplicates a file handle. You can use the dup() function to save the file handle corresponding to the stdout standard stream.
d. The fdopen() function opens a stream that has been duplicated with the dup() function.
49. What is the purpose of realloc( ) ?
50. 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.
a. 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.
51. What is the heap ?
a. The heap is where malloc(), calloc(), and realloc() get memory.
b. 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().
c. 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.
d. 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.
e. 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.
f. 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.)
g. In some environments, if a program doesn’t deallocate everything it allocated, memory stays unavailable even after the program ends.
52. How do you use a pointer to a function ?
d. After you’ve gotten the declaration of pf, you can #include and assign the address of strcmp() to pf: pf = strcmp;
53. 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.
b. It is the starting function
c. It returns an int value to the environment that called the program
d. Recursive call is allowed for main( ) also.
e. It is a user-defined function
f. Program execution ends when the closing brace of the function main( ) is reached.
g. It has two arguments 1)argument count and 2) argument vector (represents strings passed).
h. Any user-defined name can also be used as parameters for main( ) instead of argc and argv
54. 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.
55. 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.
b. 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.
c. 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.
d. If your source code contains any conditional preprocessor directives (such as #if), the preprocessor evaluates the condition and modifies your source code accordingly.
56. 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.
b. 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).
c. 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
57. What is the easiest sorting method to use ?
a. The answer is the standard library function qsort(). It’s the easiest sort by far for several reasons:
c. Void qsort(void *buf, size_t num, size_t size, int (*comp)(const void *ele1, const void *ele2));
58. 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.
b. 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.
c. 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.
d. 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.
59. What are the standard predefined macros ?
b. _ _LINE_ _ Inserts the current source code line number in your code.
_ _FILE_ _ Inserts the current source code filename in your code.
_ _ 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.
Click the following link to download the C questions in pdf format:
http://www.4shared.com/file/234231604/31e7af73/pdf-C_Interview_Questions.html
Tags Aptitude, C-Questions