Thursday, 6 August 2015

C Interview Questions

Explain i = (j++, k++) and while (i = (rand() % 100), i != 50)
Here, the comma operator is used to execute three expressions in one line: assign k to i, increment j, and increment k. The value that i receives is always the rightmost expression.
In while: the comma operator separates two expressions, each of which is evaluated for each iteration of the while statement. The first expression, to the left of the comma, assigns i to a random number from 0 to 99.The second expression, which is more commonly found in a while statement, is a conditional expression that tests to see whether i is not equal to 50.


How can you tell whether a loop ended prematurely?
Generally, loops are dependent on one or more variables. Your program can check those variables outside the loop to ensure that the loop executed properly


What is the difference between goto and long jmp( ) and setjmp()?
A goto statement implements a local jump of program execution, and the longjmp() and setjmp() functions implement a nonlocal, or far, jump of program execution.When your program calls setjmp(), the current state of your program is saved in a structure of type jmp_buf. Later, your program can call the longjmp() function to restore the program's state as it was when you called setjmp(). Unlike the goto statement, the longjmp() and setjmp() functions do not need to be implemented in the same function.However, there is a major drawback to using these functions: your program, when restored to its previously saved state, will lose its references to any dynamically allocated memory between the longjmp() and the setjmp(). This means you will waste memory for every malloc() or calloc() you have implemented


Can an array be an lvalue?
Is an array an expression to which we can assign a value? The answer to this question is no, because an array is composed of several separate array elements that cannot be treated as a whole for assignment purposes.It should be noted here that unlike arrays, structures can be treated as lvalues.


Is left-to-right or right-to-left order guaranteed for operator precedence?
The simple answer to this question is neither. The C language does not always evaluate left-to-right or right-to-left. Generally, function calls are evaluated first, followed by complex expressions and then simple expressions.Additionally, most of today's popular C compilers often rearrange the order in which the expression is evaluated in order to get better optimized code. You therefore should always implicitly define your operator precedence by using parentheses.


Can a variable be both const and volatile?
The volatile keyword is intended to prevent the compiler from applying any optimizations on objects that can change in ways that cannot be determined by the compiler.Objects declared as volatile are omitted from optimization because their values can be changed by code outside the scope of current code at any time. The system always reads the current value of a volatile object from the memory location rather than keeping its value in temporary register at the point it is requested. 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(hardware). For instance, the timer structure was accessed through a volatile const pointer


How can you determine the maximum value that a numeric variable can hold?
The easiest way to find out how large or small a number that a particular type can hold is to use the values defined in the ANSI standard header file limits.h.


When should a type cast be used?
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.


What is meant by "bit masking"?
Bit masking means selecting only certain bits from byte(s) that might have many bits set. To examine some bits of a byte, the byte is bitwise "ANDed" with a mask that is a number consisting of only those bits of interest.


Are bit fields portable?
Bit fields are not portable. Because bit fields cannot span machine words, and because the number of bits in a machine word is different on different machines, a particular program using bit fields might not even compile on a particular machine.


What is meant by high-order and low-order bytes?
We generally write numbers from left to right, with the most significant digit first.The byte holding the least significant 8 bits is called the least significant byte, or low-order byte. The byte containing the most significant 8 bits is the most significant byte, or high- order byte.


Why should I prototype a function?
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(same argument types in same order) and that no erroneous type conversions are taking place. prototype: int some_func(int, char*, long);


What is a static function?
A static function is a function whose scope is limited to the current source file.


Is it possible to execute code even after the program exits the main() function?
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 atexit() function.the LIFO method is used. The atexit() function can come in handy when you want to ensure that certain functions (such as closing your program's data files) are performed before your program terminates.


What does a function declared as PASCAL do differently?
A C function declared as PASCAL uses a different calling convention than a "regular" C function. Normally, C function parameters are passed right to left; with the PASCAL calling convention, the parameters are passed left to right.Functions that use the PASCAL calling convention are more efficient than regular C functions—the function calls tend to be slightly faster. Microsoft Windows is an example of an operating environment that uses the PASCAL calling convention


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


What will the preprocessor do for a program?
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.A preprocessor directive is a statement (such as #define) that gives the preprocessor specific instructions on how to modify your source code.


What is the benefit of using #define to declare a constant?
it is best to put #define statements in an include file so that several modules can use the same constant value.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


What is the benefit of using enum to declare a constant?
constants declared with enum are automatically generated by the compiler. constants declared with enum tend to be more readable to the programmer.  enumerated constants can usually be inspected during a debugging session


How are portions of a program disabled in demo versions?
If you are distributing a demo version of your program, the preprocessor can be used to enable or disable portions of your program.
#if DEMO_VERSION
     printf("Sorry! You can't save documents using the DEMO version of
             this program!\n");
     return(0);
#endif
As a better alternative, you could define DEMO_VERSION in your compiler options when compiling and avoid having to change the source code for the program.


How can type-insensitive macros be created?
A type-insensitive macro is a macro that performs the same basic operation on different data types. This task can be accomplished by using the concatenation operator to create a call to a type-sensitive function based on the parameter passed to the macro. The following program provides an example:
#include <stdio.h>
#define SORT(data_type) sort_ ## data_type
void sort_int(int** i);
void sort_long(long** l);
void sort_float(float** f);
void sort_string(char** s);


What is a pragma?
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 using pragma loop_opt(on)


What is #line used for?
The #line preprocessor directive is used to reset the values of the __LINE__ and __FILE__ symbols, respectively. This directive is commonly used in fourth-generation languages that generate C language source files.


What is the difference between a string copy (strcpy) and a memory copy (memcpy)? When should each be used?
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 (\0) 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.


How can I pad a string to a known length?
printf("%-10.10s", data);


How can I convert a number to a string?
The standard C library provides itoa(),ltoa(), ultoa() for converting numbers of all formats (integers, longs, floats, and so on) to strings and vice versa.
itoa(num, str, 10); //the third is the base, or radix, to be used when converting the number
You can use atof(),atoi(),atol() for conversion from strings


Can the sizeof operator be used to tell the size of an array passed to a function?
No. There's no way to tell, at runtime, how many elements are in an array parameter just by looking at the array parameter itself. Remember, passing an array to a function is exactly the same as passing a pointer to the first element


Is it better to use a pointer to navigate an array of values, or is it better to use a subscripted array name?
It's easier for a C compiler to generate good code for pointers than for subscripts.


Can you assign a different address to an array tag?
No,An array is an object; the array tag is a pointer to the first element in that object For an external or static array, the array tag is a constant value known at link time. An array tag is not a pointer.In one special case, it looks as if you can change an array tag:
void  f( char a[ 12 ] ){
       ++a;
    }
The trick here is that array parameters aren't really arrays. They're really pointers.


What is the difference between array_name and &array_name?
One is a pointer to the first element in the array; the other is a pointer to the array as a whole.


What is indirection?
If you declare a variable, its name is a direct reference to its value. If you have a pointer to a variable, or any other object in memory, you have an indirect reference to its value. If p is a pointer, the value of p is the address of the object. *p means "apply the indirection operator to p";


 What is a void pointer?
A void pointer is a C convention for "a raw address." The compiler has no idea what type of object a void pointer "really points to." If you write void *p p doesn't point to a void. A void pointer is used for working with raw memory or for passing a pointer to an unspecified type.
 void *memcpy( void *addr1, void *addr2, size_t n ) void pointers here mean that this is raw memory being copied. NUL characters (zero bytes) aren't significant, and just about anything can be copied.


Is NULL always equal to 0(zero)?
The answer depends on what you mean by "equal to." If you mean "compares equal to," then yes, NULL is always equal to 0. That's the whole point of the definition of a null pointer. If you mean "is stored the same way as an integer zero," the answer is no, not necessarily. That's the most common way to store a null pointer.
What does it mean when a pointer is used in an if statement?
Any time a pointer is used as a condition, it means "Is this a non-null pointer?" A pointer can be used in an if, while, for, or do/while statement, or in a conditional expression.


Can you add pointers together?
No, you can't add pointers together. The only time the addition of pointers might come up is if you try to add a pointer and the difference of two pointers: p = p + p2 - p1;


Can the size of an array be declared at runtime?
No. In an array declaration, the size must be known at compile time. You can't specify a size that's known only at runtime. For example, if i is a variable, you can't write code like this: char array[i];  Some languages provide this latitude. C doesn't. 


Difference between  malloc() or calloc()?
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. 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. 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


What is the heap?
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().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


What is the difference between NULL and NUL?
NULL is a macro defined in <stddef.h> for the null pointer.NUL is the name of the first character in the ASCII character set. It corresponds to a zero value.


What is a "null pointer assignment" error? What are memory faults, and core dumps?
If the program tries to write to the area where the NULL pointer points to, 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.core dumped and Memory fault are messages meaning that a pointer or an array subscript was wildly out of bounds.They aren't restricted to null pointer problems.


How do you print an address?
The safest way is to use printf() (or fprintf() or sprintf()) with the %P specification. That prints a void pointer (void*) printf( "%P\n", (void*) buffer );


What is a stream and how to redirect and restore a standard stream?
A stream is a continuous series of bytes that flow into or out of your program. Input and output from devices such as the mouse, keyboard, disk, screen, modem, and printer are all handled with streams. In DOS, redirection is accomplished using the redirection characters, < and >. C:>PRINTIT < STRINGS.TXT. you can redirect a standard stream from within your program by using the standard C library function named freopen(): freopen("output.txt", "w", stdout); 


By using the standard C library functions named dup() and fdopen(), you can restore a standard stream such as stdout to its original state. The dup() function duplicates a file handle. You can use the dup() function to save the file handle corresponding to the stdout standard stream. The fdopen() function opens a stream that has been duplicated with the dup() function.


What is the difference between text and binary modes?
Text streams are interpreted, with a maximum length of 255 characters. With text streams, carriage return/line feed combinations are translated to the newline \n character and vice versa. Binary streams are uninterpreted and are treated one byte at a time with no translation of characters. 


How do you determine whether to use a stream function or a low-level function?
you should always use buffered stream functions when accessing nonshared files, and you should always use the low-level functions when accessing shared files.


How do you list a file's date and time?
The file attributes are stored in the find_t.attrib structure member. A file's date and time are stored in the find_t structure returned from the _dos_findfirst() and _dos_findnext() functions.The date and time stamp of the file is stored in the find_t.wr_date and find_t.wr_time structure members. 


How do you view the PATH?
Your C compiler library contains a function called getenv() that can retrieve any specified environment variable. It has one argument, which is a pointer to a string containing the environment variable you want to retrieve. It returns a pointer to the desired environment string on successful completion.


How can I open a file so that other programs can update it at the same time?
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.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.by using the SH_DENYWR shared flag you instruct the compiler that your program is going to deny any writing or reading attempts by other programs.


What is the difference between a free-standing and a hosted environment?
Embedded systems don't necessarily have any sort of file system, or much of an operating system at all. The ANSI/ISO standard calls these "free-standing" systems, and it doesn't require them to provide anything except the language itself. The alternative is a program running on a PC or a mainframe or something in-between; that's a "hosted" environment.


How do I determine whether a character is numeric, alphabetic, and so on?
The header file ctype.h defines various functions for determining what class a character belongs to


What are multibyte characters?
Multibyte characters are another way to make internationalized programs easier to write. Specifically, they help support languages such as Chinese and Japanese that could never fit into eight-bit characters.

No comments:

Post a Comment