Vous êtes sur la page 1sur 14

C Interview questions and answers What are near and far pointers?

Near and Far pointers are system specific and the use of it, has been decreased over the years, it has now become obsolete. These are supported by 16-bit programmin g languages. To know the machine that doesnt require these kinds of pointers, use a preprocessor or remove the unnecessary near, far pointer keywords. How can I change the size of the dynamically allocated array? You can change the size of the array if it is defined dynamically, by using the realloc() function. realloc() functions syntax is written as: dynarray = realloc(dynarray, 20 * sizeof(int)); But, realloc() function cant just enlarge the memory, and this memory allocation depends on the space available in the system. If realloc() cant find the space av ailable, then it returns null pointer. How to write a multi-statement macro? Macro are simple statements which are written to, dynamically execute the method or function. The function call syntax is: MACRO(arg1, arg2); Macro can be included with the conditional statements using the external else cl ause. You can include simple expressions in macro with no declarations or loops like: #define FUNC(arg1, arg2) (expr1, expr2, expr3) What s the right way to use errno? The errors should be checked by return values. Errno defines among various cause s of an error, such as File not found or Permission denied. Errno detects only when a function doesnt have a unique or unambiguous errors. Errno can be set manually to 0 to find the errors. Error messages can be made useful if the program name w ith the error can be printed so that the error can be noticed and solved. Rohit Sharma 12-16-2011 03:48 AM C Interview questions and answers Why can t I perform arithmetic on a void* pointer? There are no arithmetic operations that can be performed on void* pointer is bec ause the compiler doesnt know the size of the pointed objects. Arithmetic operati ons can only be done on the pointed objects. Some compilers make it an exception to perform the arithmetic functions on the pointer. How can I return multiple values from a function? A function can return multiple values in several ways by using the pointers. The se include the examples like hypothetical calculation of polar-to-rectangular co ordinate functions. The pointer allows you to have a function in which you can p ass multiple values and use them. Example code: #include polar_to_rectangular(double a, double b, double *xp, double *yp) { a=10; b=20; *xp = a; *yp = b; } What s the total generic pointer type? There is nothing like total generic pointer type, only void* holds the object (i .e. data) pointers. Converting function pointer to type void* is not a portable

and it is not appropriate to convert it also. You can use any function type like int*() or void*(), these pointers can be treated as a generic function pointer. The best way to have the portability, is to use void* and a generic pointer com bination. Rohit Sharma 12-16-2011 03:48 AM C Interview questions and answers Which one to choose from "initialization lists" or "assignment", for the use in the constructor? Initialization list consists of all the member objects, which a constructor init ializes. By doing this, performance of the execution increases and compiler does faster processing in the case of initialization list. This is better than the a ssignment as it is an inefficient way to represent the objects and the performan ce also degrades, when it gets used. The code runs faster by using the initializ ation list rather than the assignment. Can this pointer by used in the constructor? It is not advised to use this pointer inside the constructor, because of the objec t initialization, as it takes more time for the object to be ready for the execu tion. You can use this pointer in the constructor body part and also in the initia lization list. The rules of the programming language have to be known before usi ng this operator in the constructor. What is the "Named Constructor Idiom"? Named constructor idiom is a technique that gives better intuitive and safer con struction operations for user to perform in the class. The way by which the cons tructor name and the class name can be differentiated is by storing the name in the parameter list. Using this idiom declaration of all the classs constructor me thod can be used in private and protected sections. These are the static methods which are used to return the objects of that class in which the constructor is defined. For example: class t { public: t(float x); t(float r); // ERROR: Overload is Ambiguous: t::t(float) }; int main() { t p = t(5.7); // Ambiguous: Which coordinate system? // Your statements } To solve this ambiguity we use the Named Constructor Idiom: #include // To get std::sin() and std::cos() class t { public: static t rectangular(float x); // Rectangular coord s static Point polar(float radius); // Polar coordinates // These static methods are the so-called "named constructors" }

C - scope of static variables - August 06, 2008 at 13:10 PM by Amit Satpute Define the scope of static variables.

The scope of a static variable is local to the block in which the variable is de fined. However, the value of the static variable persists between two function c alls. C - scope of static variables - Jan 11, 2010 at 14:55 PM by Vidya Sagar Define the scope of static variables. Static variables in C have the scopes; 1. Static global variables declared at the top level of the C source file have t he scope that they can not be visible external to the source file. The scope is limited to that file. 2. Static local variables declared within a function or a block, also known as l ocal static variables, have the scope that, they are visible only within the blo ck or function like local variables. The values assigned by the functions into s tatic local variables during the first call of the function will persist / prese nt / available until the function is invoked again. The static variables are available to the program, not only for the function / b lock. It has the scope within the current compile. When static variable is decla red in a function, the value of the variable is preserved , so that successive c alls to that function can use the latest updated value. The static variables are initialized at compile time and kept in the executable file itself. The life ti me extends across the complete run of the program. Static local variables have local scope. The difference is, storage duration. Th e values put into the local static variables, will still be present, when the fu nction is invoked next time. - What are volatile variables? - August 06, 2008 at 13:10 PM by Amit Satpute What are volatile variables? Volatile variables get special attention from the compiler. A variable declared with the volatile keyword may be modified externally from the declaring function . If the keyword volatile is not used, the compiler optimization algorithms might consider this to be a case of infinite loop. Declaring a variable volatile indic ates to a compiler that there could be external processes that could possibly al ter the value of that variable. e.g.: A variable that might be concurrently modified by multiple threads may be declar ed volatile. Variables declared to be volatile will not be optimized by the comp iler. Compiler must assume that their values can change at any time. However, op erations on a volatile variable are still not guaranteed to be atomic. C - What are volatile variables? - Jan 11, 2010 at 12:44 PM by Vidya Sagar What are volatile variables? Volatile variables are like other variables except that the values might be chan ged at any given point of time only by some external resources. Ex: volatile int number; The value may be altered by some external factor, though if it does not appear t o the left of the assignment statement. The compiler will keep track of these vo

latile variables. meaning of "Segmentation violation" - August 06, 2008 at 13:10 PM by Amit Satput e Explain the meaning of "Segmentation violation". A segmentation violation usually indicates an attempt to access memory which doe sn t even exist. C - meaning of "Segmentation violation" - Jan 11, 2010 at 12:15 PM by Vidya Saga r Explain the meaning of "Segmentation violation". Segmentation violation usually occurs at the time of a programs attempt for acces sing memory location, which is not allowed to access. The following code should create segmentation violation. main() { char *hello = Hello World; *hello = h; } At the time of compiling the program, the string hello world is placed in the bina ry mark of the program which is read-only marked. When loading, the compiler pla ces the string along with other constants in the read-only segment of the memory . While executing a variable *hello is set to point the character h , is attempted to write the character h into the memory, which cause the segmentation violation. And, compiler does not check for assigning read only locations at compile time. C - What is "Bus error"? - August 06, 2008 at 13:10 PM by Amit Satpute What is "Bus error"? A bus error indicates an attempt to access memory in an illegal way,perhaps due to an unaligned pointer. C - What is "Bus error"? - Jan 11, 2010 at 12:40 PM by Vidya Sagar What is "Bus error"? A bus error is certain undefined behavior result type. The cause for such error on a system could not be specified by the C language. The memory accessibility whi ch CPU could not address physically, bus error occurs. Also, any fault detected by a device by the computer system can also be a bus error. These errors caused by p rograms that generate undefined behavior which C language no longer specifies wh at can happen. recursion in C - Jan 11, 2010 at 9:12 am by Vidya Sagar Define recursion in C. Calling a function by itself is known as recursion. Any function can call any fu nction including itself. In this scenario, if it happens to invoke a function by itself, it is recursion. One of the instructions in the function is a call to t he function itself, usually the last statement. In some ways it is similar to lo oping. When the result of one time call of a function is the input for the next t ime call of the function, recursion is one of the best ways. For example, calcula ting factorial, in which the product of previous digit factorial is the input fo r the next digits factorial. The process of calling a function by itself is known as recursion. Recursion is

generally used when the result of the current function call is the input to the successive call of itself. For example, factorial of a digit. By definition, the f actorial of the current digit is the factorial of its previous digit and the dig it. In order to get the factorial of the previous digit, the same function shoul d return the factorial. Thus the result of the previous execution of the function is one of the inputs o f the current execution. The process continues until an exit condition returns t rue. C - recursion in C - posted on July 20th, 2008 at 8:47 am by Siri Define recursion in C. A programming technique in which a function may call itself. Recursive programmi ng is especially well-suited to parsing nested markup structures C - static variable mean in C - Jan 11th, 2010 at 9:17 am by Vidya Sagar What does static variable mean in C? Static variable is available to a C application, throughout the life time. At th e time of starting the program execution, static variables allocations takes pla ce first. In a scenario where one variable is to be used by all the functions (w hich is accessed by main () function), then the variable need to be declared as static in a C program. The value of the variable is persisted between successive calls to functions. One more significant feature of static variable is that, th e address of the variable can be passed to modules and functions which are not i n the same C file. C - static variable mean in C - posted on July 20th, 2008 at 8:47 am by Siri What does static variable mean in C? static is an access qualifier that limits the scope but causes the variable to e xist for the lifetime of the program. This means a static variable is one that i s not seen outside the function in which it is declared but which remains until the program terminates. It also means that the value of the variable persists be tween successive calls to a function. The value of such a variable will remain a nd may be seen even after calls to a function. One more thing is that a declarat ion statement of such a variable inside a function will be executed only once. What are bitwise shift operators? The bitwise operators are used for shifting the bits of the first operand left o r right. The number of shifts is specified by the second operator. Expression << or >> number of shifts Ex: number<<3;/* number is an operand - shifts 3 bits towards left*/ number>>2; /* number is an operand shifts 2 bits towards right*/ The variable number must be an integer value. For leftward shifts, the right bits those are vacated are set to 0. For rightwar d shifts, the left bits those are vacated are filled with 0s based on the type of the first operand after conversion. If the value of number is 5, the first statement in the above example results 40 a nd stored in the variable number.

If the value of number is 5, the second statement in the above example results 0 ( zero) and stored in the variable number. C - bitwise shift operators - August 06, 2008 at 13:10 PM by Amit Satpute What are bitwise shift operators? << - Bitwise Left-Shift Bitwise Left-Shift is useful when to want to MULTIPLY an integer (not floating p oint numbers) by a power of 2. Expression: a << b This expression returns the value of a multiplied by 2 to the power of b. >> - Bitwise Right-Shift Bitwise Right-Shift does the opposite, and takes away bits on the right. Expression: a >> b This expression returns the value of a divided by 2 to the power of b. use of bit fieild - August 06, 2008 at 13:10 PM by Amit Satpute Explain the use of bit fieild. Bit Fields allow the packing of data in a structure. This is especially useful when memory or data storage is at a premium The maximum length of the field should be less than or equal to the integer word length of the computer.some compilers may allow memory overlap for the fields.S ome store the next field in the next word. C lets us do this in a structure definition by putting :bit length after the var iable: struct pack { unsigned int funny_int:9; }p; Also, Boolean datatype flags can be stored compactly as a series of bits using t he bits fields. Each Boolean flag is stored in a separate bit. C - use of bit fieild - Jan 11, 2010 at 17:40 PM by Vidya Sagar Explain the use of bit fieild. Packing of data in a structured format is allowed by using bit fields. When the memory is a premium, bit fields are extremely useful. For example: - Picking multiple objects into a machine word : 1 bit flags can be compacted - Reading external file formats : non-standard file formats could be read in, li ke 9 bit integers This type of operations is supported in C language. This is achieved by putting :bit length after the variable. Example: struct packed_struct unsigned int unsigned int unsigned int unsigned int unsigned int unsigned int } pack; { var1:1; var2:1; var3:1; var4:1; var5:4; funny_int:9;

packed-struct has 6 members: four of 1 bit flags each, and 1 4 bit type and 1 9 bit funny_int. C packs the bit fields in the structure automatically, as compactly as possible, which provides the maximum length of the field is less than or equal to the int eger word length the computer system. The following points need to be noted while working with bit fields: The conversion of bit fields is always integer type for computation Normal types and bit fields could be mixed / combined Unsigned definitions are important. - purpose of "register" keyword - August 06, 2008 at 13:10 PM by Amit Satpute What is the purpose of "register" keyword? It is used to make the computation faster. The register keyword tells the compiler to store the variable onto the CPU regis ter if space on the register is available. However, this is a very old technique . Todays processors are smart enough to assign the registers themselves and henc e using the register keyword can actually slowdown the operations if the usage i s incorrect. C - purpose of "register" keyword - Jan 11, 2010 at 12:55 PM by Vidya Sagar What is the purpose of "register" keyword? The keyword register instructs the compiler to persist the variable that is being declared , in a CPU register. Ex: register int number; The persistence of register variables in CPU register is to optimize the access. Even the optimization is turned off; the register variables are forced to store in CPU register. C - use of "auto" keyword - August 06, 2008 at 13:10 PM by Amit Satpute Explain the use of "auto" keyword. When a certain variable is declared with the keyword auto and initialized to a cer tain value, then within the scope of the variable, it is reinitialized upon bein g called repeatedly. C - use of "auto" keyword - Jan 11, 2010 at 14:50 PM by Vidya Sagar Explain the use of "auto" keyword. The keyword auto is used extremely rare. A variable is set by default to auto. The declarations: auto int number; and int number; has the same meaning. The variables of type static, extern and register need to be explicitly declared, as their need is very specific. The variables other than the above three are implied to be of auto variables. For better readability auto keyword can be used. <<Previous Next>> function prototype - August 06, 2008 at 13:10 PM by Amit Satpute Explain function prototype.

A function prototype is a mere declaration of a function. It is written just to specify that there is a function that exists in a program. It is necessary to declare the return type and the arguments types along with th eir modifiers. However, it is not necessary to declare the names of the argument s. C - function prototype - Jan 11, 2010 at 12:50 PM by Vidya Sagar Explain function prototype. The basic definition of a function is known as function prototype. The signature of the function is same that of a normal function, except instead of containing code, it always ends with semicolon. When the compiler makes a single pass over each and every file that is compiled. If a function call is encountered by the compiler, which is not yet been define d, the compiler throws an error. One of the solution for the above is to restructure the program, in which all th e functions appear only before they are called in another function. Another solution is writing the function prototypes at the beginning of the file , which ensures the C compiler to read and process the function definitions, bef ore there is a change of calling the function. If prototypes are declared, it is convenient and comfortable for the developer to write the code of those functio ns which are just the needed ones. <<Previous Next>> C - purpose of "extern" keyword - August 06, 2008 at 13:10 PM by Amit Satpute What is the purpose of "extern" keyword in a function declaration? The declaration of functions defaults to external linkage. The only other storag e class possible for a function is static, which must be specified explicitly. I t cannot be applied to a block scope function declaration and results in interna l linkage. C - purpose of "extern" keyword - Jan 11, 2010 at 15:40 PM by Vidya Sagar What is the purpose of "extern" keyword in a function declaration? The keyword extern indicates the actual storage of the variable is visible , or bo dy of a function is defined elsewhere, commonly in a separate source code. This extends the scope of the variables or functions to be used across the file scope . Example: extern int number; <<Previous Next>>

- use of fflush() function - August 06, 2008 at 13:10 PM by Amit Satpute Explain the use of fflush() function. In ANSI, fflush() [returns 0 if buffer successfully deleted / returns EOF on an error] causes the system to empty the buffer associated with the specified outpu t stream. It undoes the effect of any ungetc() function if the stream is open for input. T he stream remains open after the call. If stream is NULL, the system flushes all open streams. However, the system automatically deletes buffers when the stream is closed or e

ven when a program ends normally without closing the stream. C - use of fflush() function - Jan 11, 2010 at 16:16 PM by Vidya Sagar Explain the use of fflush() function. The fflush() function is used for clearing the buffer before closing the file. I t flushes the currently available pending data of files. All the output units wi ll be flushed, in case the parameter is NULL. It is useful when some set of writ es has completed before, like responding to a request. <<Previous Next>>

- malloc() and calloc() function - August 06, 2008 at 13:10 PM by Amit Satpute Explain the difference between malloc() and calloc() function. Both functions are used to dynamically allocate the memory. The difference is th at calloc initializes the allocated memory to 0 or Null while malloc contains ga rbage values. C - malloc() and calloc() function - Jan 11, 2010 at 16:16 PM by Vidya Sagar Explain the difference between malloc() and calloc() function. The following are the differences between malloc() and calloc(): - Byte of memory is allocated by malloc(), whereas block of memory is allocated by calloc(). - malloc() takes a single argument, the size of memory, where as calloc takes tw o parameters, the number of variables to allocate memory and size of bytes of a single variable - Memory initialization is not performed by malloc() , whereas memory is initial ized by calloc(). - malloc(s) returns a pointer with enough storage with s bytes, where as calloc( n,s) returns a pointer with enough contiguous storage each with s bytes.

<<Previous

Next>>

C - strcpy() and memcpy() function - August 06, 2008 at 13:10 PM by Amit Satpute Explain the difference between strcpy() and memcpy() function. strcpy() copies a string until it comes across the termination character \0. With memcopy(), the programmer needs to specify the size of data to be copied. strncp y() is similar to memcopy() in which the programmer specifies n bytes that need to be copied. C - strcpy() and memcpy() function - Jan 11, 2010 at 16:16 PM by Vidya Sagar Explain the difference between strcpy() and memcpy() function. The following are the differences between strcpy() and memcpy(): - memcpy() copies specific number of bytes from source to destinatio in RAM, whe re as strcpy() copies a constant / string into another string. - memcpy() works on fixed length of arbitrary data, where as strcpy() works on n ull-terminated strings and it has no length limitations.

- memcpy() is used to copy the exact amount of data, whereas strcpy() is used of copy variable-length null terminated strings. <<Previous Next>>

- exit() and _exit() function - August 06, 2008 at 13:10 PM by Amit Satpute Explain the difference between exit() and _exit() function. exit() does cleanup work like closing file descriptor, file stream and so on, wh ile _exit() does not. C - exit() and _exit() function - Jan 11, 2010 at 16:16 PM by Vidya Sagar Explain the difference between exit() and _exit() function. The following are the differences between exit() and _exit() functions: - io buffers are flushed by exit() and executes some functions those are registe red by atexit(). - _exit() ends the process without invoking the functions which are registered b y atexit(). <<Previous Next>> - Compare array with pointer - August 06, 2008 at 13:10 PM by Amit Satpute Compare array with pointer. The following declarations are NOT the same: char *p; char a[20]; The first declaration allocates memory for a pointer; the second allocates memor y for 20 characters. C - Compare array with pointer - Jan 11, 2010 at 18:10 PM by Vidya Sagar Define pointer in C. A pointer is an address location of another variable. It is a value that designa tes the address or memory location of some other value (usually value of a varia ble). The value of a variable can be accessed by a pointer which points to that variable. To do so, the reference operator (&) is pre-appended to the variable t hat holds the value. A pointer can hold any data type, including functions. <<Previous Next>> C - What is NULL pointer? - August 06, 2008 at 13:10 PM by Amit Satpute What is NULL pointer? A null pointer does not point to any object. NULL and 0 are interchangeable in pointer contexts.Usage of NULL should be consi dered a gentle reminder that a pointer is involved. It is only in pointer contexts that NULL and 0 are equivalent. NULL should not b e used when another kind of 0 is required. C - What is NULL pointer? - Jan 11, 2010 at 18:10 PM by Vidya Sagar What is NULL pointer? A pointer that points to a no valid location is known as null pointer. Null poin ters are useful to indicate special cases. For example, no next node pointer in case of a linked list. An indication of errors that pointers returned from funct ions.

Test Java skills New C bit operations C function pointers C functions C pointers C preprocessor C structures Download C++/Oracle FAQ C++ Java Oops Data structure Operating system Database concepts Linux Networking CV Cover letter HR Job interviews Soft skills Group discussion

#pragma statements <<Previous Next>> C - #pragma statements - August 06, 2008 at 13:10 PM by Amit Satpute Define #pragma statements. The #pragma Directives are used to turn ON or OFF certain features. They vary fr om compiler to compiler. Examples of pragmas are: #pragma m #pragma #pragma #pragma #pragma startup // you can use this to execute a function at startup of a progra exit warn warn warn // you can use this to execute a function at exiting of a program rvl // used to suppress return value not used warning par // used to suppress parameter not used warning rch // used to suppress unreachable code warning

C - #pragma statements - Jan 11, 2010 at 18:10 PM by Vidya Sagar Define #pragma statements. The @pragma is a compiler specific directive, which can be used by the vendors of that compiler. For example, #pragma is utilized for allowing specific error mess ages suppression and to manage head and stack debugging. <<Previous Next>>

C - advantages of using macro - August 06, 2008 at 13:10 PM by Amit Satpute Describe the advantages of using macro. In modular programming, using functions is advisable when a certain code is repe ated several times in a program. However, everytime a function is called the con trol gets transferred to that function and then back to the calling function. Th is consumes a lot of execution time. One way to save this time is by using macro

s. Macros substitute a function call by the definition of that function. This sa ves execution time to a great extent. <<Previous Next>>

C - self-referential structure - August 06, 2008 at 13:10 PM by Amit Satpute Explain with an example the self-referential structure. A self referential structure is used to create data structures like linked lists , stacks, etc. Following is an example of this kind of structure: struct struct_name { datatype datatypename; struct_name * pointer_name; }; C - self-referential structure - Jan 11, 2010 at 18:10 PM by Vidya Sagar Explain with an example the self-referential structure. A self-referential structure is one of the data structures which refer to the po inter to (points) to another structure of the same type. For example, a linked l ist is supposed to be a self-referential data structure. The next node of a node is being pointed, which is of the same struct type. For example, typedef struct listnode { void *data; struct listnode *next; } linked_list; In the above example, the listnode is a self-referential structure because the * next is of the type sturct listnode. - structures and Union - Jan 11th, 2010 at 9:17 am by Vidya Sagar Explain structure. A structure is a user defined data type, which groups a set of data types. It is a collection of variables of different type under single name. A structure prov ides a convenience to group of related data types. A structure can contain varia bles, pointers, other structures, arrays or pointers. A structure is defined wit h the keyword struct Ex: struct employee { int empid; char name[20]; float salary; }; .. .. struct employee Catherina; C - structures and Union - Jan 11, 2010 at 18:10 PM by Vidya Sagar Describe structures and Union in brief. Structures: Structures provide a convenient method for handling related group of data of var ious data types.

Structure definition: struct tag_name { data type member1; data type member2; } Example: struct library_books { char title[20]; char author[15]; int pages; float price; }; The keyword struct informs the compiler for holding fields ( title, author, page s and price in the above example). All these are the members of the structure. E ach member can be of same or different data type. The tag name followed by the keyword struct defines the data type of struct. The tag name library_books in the above example is not the variable but can be visu alized as template for the structure. The tag name is used to declare struct var iables. Ex: struct library_books book1,book2,book3; The memory space is not occupied soon after declaring the structure, being it a template. Memory is allocated only at the time of declaring struct variables, li ke book1 in the above example. The members of the structure are referred as - bo ok1.title, book1.author, book1.pages, book1.price. Unions Unions are like structures, in which the individual data types may differ from e ach other. All the members of the union share the same memory / storage area in the memory. Every member has unique storage area in structures. In this context, unions are utilized to observe the memory space. When all the values need not a ssign at a time to all members, unions are efficient. Unions are declared by usi ng the keyword union , just like structures. Ex: union item { int code; float price; }; The members of the unions are referred as - book1.title, book1.author, book1.pag es, book1.price. <<Previous Next>>

- properties of Union - Jan 11, 2010 at 18:10 PM by Vidya Sagar What are the properties of Union? A union is utilized to use same memory space for all different members of union. Union offers a memory section to be treated for one variable type , for all mem

bers of the union. Union allocates the memory space which is equivalent to the m ember of the union , of large memory occupancy.

Vous aimerez peut-être aussi