Vous êtes sur la page 1sur 36

C interview questions and answers

QUESTION - Which of the following is not correct about calloc(...)?


-It allocates a block of memory for an array of elements of a certain size.
-It allocates an array in memory with elements initialized to 0 and returns a pointer to the allocated space.
-It allocates memory blocks and returns a void pointer to the allocated space, or NULL if there is insufficient memory
available.
-All of above are correct

View Answer / Hide Answer
QUESTION - How can we reduce a final size of executable?
-by using dynamic linking for libraries.
-by using static linking for libraries.
-Both are correct
-None of above are correct

View Answer / Hide Answer
C interview test - (42 questions)
C interview questions and answers for freshers
Advanced C interview questions - senior level C interview
Basic C interview questions - Frequently asked C interview
QUESTION - Which of the following is correct for "register" keyword?
-It is used to make the computation faster.
-The register keyword tells the compiler to store the variable onto the CPU register if space on the register is
available.
-Using the register keyword can actually slowdown the operations if the usage is incorrect.
-All are correct
View Answer / Hide Answer
QUESTION - Recursive data structures are almost always implemented with memory
from the __________
-stack
-heap
-processor
-RAM

View Answer / Hide Answer
ANSWER - heap
QUESTION - Which of the following is not true for main() function?
-It is the first function to be called when the program starts execution.
-The function main() invokes other functions within it.
-It returns an int value to the environment that called the program.
-Recursive call is not allowed for main()
View Answer / Hide Answer
ANSWER - Recursive call is not allowed for main()
QUESTION - Which of the following is not correct about stack?
-A stack is one form of a data structure.
-Data is stored in stacks using the FILO approach.
-Both top and rear end of the stack are accessible
-Storing data in a stack is referred to as a PUSH
View Answer / Hide Answer
ANSWER - Both top and rear end of the stack are accessible
QUESTION - Which of the following is correct for header files?
-Header files are also called as library files.
-They carry two important things: the definitions and prototypes of functions being used in a program.
-stdio.h is a header file that contains definition and prototypes of commands like printf and scanf.
-All of above are correct
View Answer / Hide Answer
ANSWER - All of above are correct
QUESTION - static variables are local in scope to the block or file in which they are
defined, but their lifespan is throughout the program.
-True
-False
View Answer / Hide Answer
ANSWER - True
QUESTION - Which of the following is not correct for static variables?
-The value of a static variable in a function is retained between repeated function calls to the same function.
-static variables are allocated on the heap
-static variables do not retain its old value between function calls
-The scope of static variable is local to the block in which it is defined.
View Answer / Hide Answer
ANSWER - static variables do not retain its old value between function calls
QUESTION - One that can be modified by the class even when the object of the class
or the member function doing the modification is const it is known as______________
-member function
-mutable member
-constant member
-none of these
View Answer / Hide Answer
ANSWER - mutable member
QUESTION - A __________is a single-parameter constructor that is declared without
the function specifier explicit.
-converting constructor
-copy constant
-dangling pointer
-none of these
View Answer / Hide Answer
ANSWER - converting constructor
QUESTION - What function should be used to release allocated memory which is no
longer needed?
-free()
-dealloc()
-release()
-dropmem()
-unalloc()
View Answer / Hide Answer
ANSWER - free()
QUESTION - What is mean by inverted file?
-A file which stores opposite records
-Locates information about data in small files that are maintained apart from actual data record
-A file which stores information about records of a system
-None of above
View Answer / Hide Answer
ANSWER - Locates information about data in small files that are maintained apart from actual data record
QUESTION - The size of a structure can be determined by
a. size of variable name
b. size of (struct tag)
-Only a
-Only b
-Both a and b
-None of these options
View Answer / Hide Answer
ANSWER - Both a and b
QUESTION - What function should be used to free the memory allocated by calloc() ?
-dealloc();
-malloc(variable_name, 0)
-free();
-memalloc(variable_name, 0)
View Answer / Hide Answer
ANSWER - free();
QUESTION - What is the similarity between a structure, union and enumeration?
-All of them let you define new values
-All of them let you define new data types
-All of them let you define new pointers
-All of them let you define new structures
View Answer / Hide Answer
ANSWER - All of them let you define new data types
QUESTION - In C, if you pass an array as an argument to a function, what actually gets
passed?
-Value of elements in array
-First element of the array
-Base address of the array
-Address of the last element of array
View Answer / Hide Answer
ANSWER - Base address of the array
QUESTION - The library function used to find the last occurrence of a character in a
string is
-strnstr()
-laststr()
-strrchr()
-strstr()
View Answer / Hide Answer
ANSWER - strrchr()
QUESTION - Identify which of the following are declarations
-extern int x;
-float square ( float x ) { ... }
-double pow(double, double);
-None of these
View Answer / Hide Answer
ANSWER - double pow(double, double);
QUESTION - When we mention the prototype of a function?
-Defining
-Declaring
-Prototyping
-Calling
View Answer / Hide Answer
ANSWER - Declaring
C interview questions - May 31, 2013 at 11:55 AM by Kshipra Singh
What do you mean by a sequential access file?
- While writing programs that store and retrieve data in a file, it is possible to designate that file into different forms.
- A sequential access file is such that data are saved in sequential order: one data is placed into the file after
another.
- If you want to access a particular data within the sequential access file, data has to be read - one data at a time,
until you reach the data you want.
Explain zero based addressing.
- The array subscripts always start at zero.
- These subscript values are used to identify the elements in the array.
- Since subscripts start at 0,arrays are said to use zero-based addressing.
Are bit fields portable?
- No, Bit fields are not portable.
- Since Bit fields cannot span machine words and the number of bits in a machine word is different on different
machines, a particular program using bit fields might not compile on some machines.
- One should avoid using bit fields except when the machines can directly address bits in memory and the compiler
can generate code.
Explain high-order and low-order bytes.
- The numbers are written from left to right in the decreasing order of significance. Similarly, the bits in a byte of
computer memory can be considered as digits of a number written in base
- The byte holding the least significant 8 bits is called the low-order byte.
- The byte holding the most significant 8 bits is the most significant byte, or high- order byte.
What are the different types of endless loops?
An endless loop can be of two types

i.) A loop that is intentionally designed to go round and round until the condition within the loop is met. Once the
condition is met, a break function gets the program out of the loop.
ii.) A loop condition written by mistake, causing the loop to run erroneously forever. Endless loops are also referred to
as infinite loops.
Why are all header files not declared in every C program?
- Declaring all header files in every program would lead to increase in the overall file size and load of the program. It
is not a good programming.
- The choice header files that you want to declare in the program depends on the commands/functions you want to
use in the program. Each header file contains different commands and functions. So we use only the files relevant to
our program.
Which one would you prefer - a macro or a function?
It actually depends on the purpose of the program!

- In case of macros, the corresponding code is inserted directly into your source code at the point where macro is
called. There is no overhead involved in using a macro.This makes the Macros more efficient and faster than
functions. However, macros are usually small and cannot handle large, complex coding constructs. So, if it is a
complex situation that the program wants to handle, functions are more suitable.

- Macros are expanded inline - this means that every time a macro occurs, the code is replicated. So, the code size in
case of usage of macros will be larger in comparison to functions.

So, the choice of using macros or functions actually depends of your requirement - speed vs program size.

If your program contains small, repeated code sections, you should use Macros. If the program requires, large
number of unique code lines - you should prefer functions.
What is break statement?
- A break statement causes the loop to terminate. The control then passes to the statement following the body of the
loop.
Explain spaghetti programming.
- Spaghetti programming refers to codes that tend to get tangled and overlapped throughout the program.
- It makes a program complex and analyzing the code becomes difficult. It usually happends due to the lack of work
experience on developer's part.
Differentiate between the = symbol and == symbol?
- The = symbol is usually used in mathematical operations. It is used to assign a value to a given variable while the
== symbol is a relational operator that is used to compare two values.
What are actual arguments?
- When some functions are created and used to perform an action on some given values, some values need to be
passed to them. The values that are passed into the called function are referred to as actual arguments.
What is a newline escape sequence?
- A newline escape sequence is represented by the \n character.
- It is used to insert a new line while displaying the output data.
- To add more spaces you can use more \n characters.
How many levels deep can include files be nested?
- As such, there is no limit to the number of levels of nested include files you can have but your compiler might run
out of stack space while trying to include an inordinately high number of files. This number depends on your hardware
configuration and compiler.

- Although it is legal to nest include files yet you must avoid it. An include level should be created only where it is
required and makes sense, like creating an include file that has an #include statement for each header required by
the module you are working with.
What are pre-processor directives?
- Pre-processor directives are placed at the beginning of a C program. They begin with # symbol.
- This is the place, where library files are specified depending on the functions to be used in the program.
- Pre-processor directives are also used for declaration of constants.
What are compound statements?
- Compound statements are made up of two or more program statements which are executed together. They can be
executed with a loop.
- Curly brackets { } are placed before and after compound statements.
- Compound statements are usually used while handling conditions in which a series of statements are executed
when a TRUE or FALSE is evaluated.
How does placing some code lines between the comment symbol help in
debugging the code?
- Placing comment symbols /* */ around a code isolates some code that the coder believes might be causing the
errors in the program, without deleting it. - If the code is correct, you can just remove the comment symbols, without
needing to retype it.
- If it is wrong, you can just remove it.
Is it possible to pass an entire structure to functions?
Yes, it is possible to pass an entire structure to a function in a call by method style. Some programmers prefer to
declare the structure globally, then pass a variable of that structure type to a function. It helps in maintaining the
consistency and uniformity in terms of argument type.
What are header files? What are their uses?
- Header files are also called as library files.
- They carry two important things: the definitions and prototypes of functions being used in a program.
- For example: stdio.h is a header file that contains definition and prototypes of commands like printf and scanf.
Is it possible to create your own header files?
- Yes, it is possible to create a customized header file.
- To do this, you just need to include the function prototypes that you want to use in your program in it, and use the
#include directive followed by the name of your header file.
Why is a semicolon (;) put at the end of every program statement?
- It is done for parsing process and compilation of the code.
- A semicolon acts as a delimiter. This tells the compiler where each statement ends, and can proceed to divide the
statement into smaller elements for checking the syntax.
How do you access the values within an array?
- Arrays contain a number of elements, depending on the size you assigned it during variable declaration.
- Each element is assigned a number from 0 to number of elements-1.
- To assign or retrieve the value of a particular element, refer to the element number. For example: if you have a
declaration that says intmarks[6];, then you have 6 accessible elements, namely: marks[0], marks[1], marks[2],
marks[3], marks[4] and marks[5].
What is the role of && operator in a program code?
- The && is also referred to as AND operator.
- When this operator is used, all conditions specified must be TRUE before the next action can be carried out.
- If any of the conditions is false, the whole statement is false.
Differentiate between functions getch() and getche().
- Both functions accept a character input value from the user.
- When getch() is used, the key that was pressed will not appear on the screen. It is automatically captured and
assigned to a variable.
- While when getche() is used, the key that was pressed by the user appears on the screen and is assigned to a
variable.
What are the various types of control structures in programming?
- Mainly there are 3 types of control structures in programming: Sequence, Selection and Repetition.
- Sequential control follows a top- down flow in executing a program. This means that step 1 is first executed,
followed by step 2 and so on.
- Selection means dealing with conditional statements. This means that the code is executed depending on the
evaluation of conditions a TRUE or FALSE. It means that not all codes may be executed and there are alternative
flows within.
- Repetitions are also called as loop structures. They will repeat one or two program statements as set by a counter.
Differentiate between the expression ++a and a++?
- With ++a, the increment happens first on variable a, and the resulting value is used. This is called as prefix
increment.
- With a++, the current value of the variable will be used in an operation. This is called as postfix increment.
What are control structures?
- Control structures decide which instructions in the program should be executed.
- This implies that the program flow may not necessarily move from one statement to the next one. Some alternative
portions may be executed depending on the conditional statements.
Explain enumerated types.
- Enumerated types allow the programmers to use more meaningful words as values to a variable.
- Each item in the enumerated type variable is actually associated with a numeric code. For an enumerated type
variable named Months can be created. Its values can be January, February,....December.
Are comments included during the compilation stage and placed in the EXE
file as well?
- No, comments encountered by the compiler are disregarded.
- Their only purpose is guidance and ease of programmer. They have no effect on the functionality of the program.
Define the scope of static variables.
The scope of a static variable is local to the block in which the variable is defined..............
Read answer
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................
Read answer
Explain the meaning of "Segmentation violation".
A segmentation violation usually indicates an attempt to access memory which doesn't even exist............
Read answer
What is "Bus error"?
A bus error indicates an attempt to access memory in an illegal way,perhaps due to an unaligned pointer...........
Read answer
Define recursion in C
A programming technique in which a function may call itself. Recursive programming is especially well-suited to
parsing nested markup structures.............
Read answer
What does static variable mean in C?
static is an access qualifier that limits the scope but causes the variable to exist for the lifetime of the
program....................
Read answer
List out differences between structures and arrays
The following are the differences between structures and arrays: - Array elements are homogeneous. Structure
elements are of different data type.............
Read answer
Define macros. What are the advantages and disadvantages of Macros?
A macro is a name given to a block of C statements as a pre-processor directive. Being a pre-processor, the block of
code is communicated to the compiler before entering............
Read answer
List out differences between pass by reference and pass by value
Pass by value always invokes / calls the function or returns a value that is based on the value. This value is passed
as a constant or a variable with value.............
Read answer
Define static identifier in C?
The static identifier is used for initializing only once, and the value retains during the life time of the program /
application. A separate memory is allocated for static variables............
Read answer
What are the auto variables? Where are they stored?
The auto variables are stored in the memory of the system. The keyword auto is optional. Many of the variables
used by the program.............
Read answer
List out differences between arrays and linked list
The difference between arrays and linked lists are: - Arrays are linear data structures. Linked lists are linear and non-
linear data structures............
Read answer
Explain the term enumerations in C
A set of named integer constants is known as an enumeration. The enumeration type declaration includes the name
of the enumeration tag and the definition of a set of named integers............
Read answer
Describe about storage allocation and scope of global, extern, static, local and register variables
The storage allocation / class determine the memory part where the storage space is allocated for variables,
functions and how long the allocation of storage continues to exist............
Read answer
Define register variables. What are the advantages of using register variables?
The variables of register type modifier will inform the compiler for storing the variables in a register of CPU.............
Read answer
What is the use of typedef?
The keyword typedef is used for defining user defined data types. A new definition of existing data types is created by
using typedef...............
Read answer
Can we specify variable field width in a scanf() format string? If possible how?
It is possible to specify variable field width in a scanf() format string. By using %s control string...........
Read answer
Out of fgets() and gets() which function is safe to use and why?
The function fgets() function is safer to use. It checks the bounds.........
Read answer
List out differences between strdup() and strcpy()
The function strcpy() will not allocate the memory space to copy..............
Read answer
What is the difference between char *a and char a[]?
For char[] array, such size is not accepted by the compiler. If the size is specified, the following are the differences
between char *a and char a[]...........
Read answer
Define void pointer
A void pointer is pointer which has no specified data type. The keyword void is preceded the pointer variable.............
Read answer
What is a const pointer?
A const pointer is not the pointer to constant, it is the constant. For example, int* const ptr; indicates that ptr is a
pointer..............
Read answer
Explain memory leak
An unwanted increase in programs is referred as a memory leak is C language. The intake of program
increases...............
Read answer
What is static memory allocation and dynamic memory allocation?
Static Memory Allocation: Memory is allocated for the declared variable by the compiler............
Read answer
What is the purpose of main( ) function?
The function main() calls / invokes other functions within it. The execution of the program always starts with main()
function...........
Read answer
What is the difference between #define and constant in C?
A #define is used as immediate constant or as a macro. Where as the constant is a variable whose value can not
change.............
Read answer
What are storage class in c?
The scope and lifetime of a variable or / and function within a C program is defined by storage class. There are four
storage classes in C............
Read answer

Tell us something about keyword "auto".
- "Automatic" is a local variable with a local lifetime.
- It is declared by auto storage-class specifier.
- This variable is visible only in the block in which it is declared.
- The value of uninitialized auto variables is undefined.
- The variables with auto storage class need to be initialised while storing them or initial values need to be assigned
to them in statements within the block.
Explain the meaning of keyword 'extern' in a function declaration.
- 'extern' modifier in a method declaration implies that the method is implemented externally.
- The program doesn't reserve any memory for a variable declared as 'extern'.
- A variable that is required to be used in every file of the project is declared globally in one file - and not inside any
function.
- 'extern' declaration of that variable is added to a header file not included in all others.
Differentiate between #include<...> and #include "..."
- #include<...> means that the directories other than the current one will be searched for the header file.
- #include "..." means that the current directory will be searched for the header file before any other directories.

Situation - The 'sizeof' operator reported a larger size than the calculated size for a structure type. What could be the
reason?

- The 'sizeof' operator shows the amount of storage needed to store an object of the specified type of operand.
- The result of applying it to a structure type name is the number of bytes including internal and trailing padding.
- This may inlcude internal leading & trailing padding used for the alignment of structure on memory boubdaries. This
may cause the error.
What does *p++ do? What does it point to?
- *p++ increments p.
- It returns the value pointed to by p before incrementation.
Explain "Bus Error".
- It is a fatal error in the execution of a machine language instruction.
- It occurs because the procesor detects an abnormal condition on its bus.
- The causes may be:
- Invalid address alignment.
- Accessing a physical address that does not correspond to any device.
- Other device specific hardware error.
What are volatile variables?
Volatile variables are like other variables except that the values might be changed 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 to the left of the assignment
statement. The compiler will keep track of these volatile variables.
C interview questions and answers for freshers

Explain the keyword continue.
How are decisions made using a switch keyword?
What is the K & R method to declare formal arguments in a function.
Give one method for declaration of formal parameters.
What is garbage value and how it can be avoided?
Give the difference between call by value and call by reference.
Which variables always contain whole numbers?
Explain recursion.
Can user defined functions be added to the library ?If yes, explain.
Explain the automatic and static storage classes.
Explain the keyword continue.
It is used to take the control to the beginning of the loop.
It bypasses the statements inside the loop, which have not been executed.
Continue statement is generally present within a loop and associated with if statement.
Example:
int i, j;
for ( i=1 ; 1<=2 ; i++)
{
for ( j=1 ; j<=2; j++)
{
if (i==j)
continue ;
printf (\n%d %d\n,i,j);
}
}
Output of program is 12
21
When the continue statement takes control it bypasses the remaining statements of the inner for loop.
How are decisions made using a switch keyword?
Switch is combined with case and default keywords to make a control statement.
Syntax: switch(integer expression)
{
case constant 1:
do this;
case constant 2:
do this;
case constant n:
do this;
default:
do this;
}
The integer expression yields an integer value.
This integer value is matched with case constant and if condition for any case is true it executes the statements
following the case statement.
If no case matches then statements following default are executed.
What is the K & R method to declare formal arguments in a function .
K & R is called as the Kernighan and Ritchie method of declaring arguments.
Example: calsum(x, y, z)
int x, y, z;
here x,y,z are the formal parameters.
Here the values x, y, z are defined in the first statement (function declaration).
Their data types are defined in the second statement.
Give one method for declaration of formal parameters.
Formal parameters can be declared using ANSI method .
In this method the data types of the parameters are defined in the function declaration.
The data types used can be integer, float, char, etc.
Example: calsum(int x, int y, int z)
Here x,y,z are the formal parameters.
What is garbage value and how it can be avoided?
If a function is not returning any specific value ,it returns data called garbage value.
Example: return(a); A
return ; B
In statement A a specified value a is returned.
In statement B no specified value present so it returns a garbage value.
To avoid the garbage value keyword void is placed before the function name.
Example: void display ( )
{
printf (welcome);
}
Give the difference between call by value and call by reference.
When a function is called it passes values of variables to called functions.
This is called as call by value and we have access to formal parameters.
Example: sum= calsum( a, b, c);
Here calsum is the function and a, b, c are the values passed.
If instead of the values the addresses of value are passed it is called as call by reference.
To pass values using call by reference pointers are used and we have access to actual parameters.
Which variables always contain whole numbers?
Pointers are the variables which always contain data in the form of whole numbers.
They store the address of other variables.
They are declared as data type *name of variable.
It also uses other operator & which returns the address of the variable.
Example; j= &i
Here j is a variable that holds the address of other variable i.
Explain recursion.
A function is called recursive if a statement within the function can call the same function.
In circular definition it is the process of defining something in terms of itself.
It is represented as rec( ).
An if statement is used within recursive statement to avoid infinite loop.
Example: rec ( int x)
{
int f;
if (x== 1)
return ( 1 );
else
f=x*rec(x-1);
return ( f );
}
Function to find the factorial of a number.
Can user defined functions be added to the library ?If yes, explain.
Yes, the user defined functions can be added to the library.
Also different compilers provide different utilities to modify functions and for c compilers utility called tlib.exe (Turbo
library) is used.
Initially create the function and then compile the file using Alt f9.
This file contains the code in machine language and then add file to the library using the command c:\.>tlib
math.lib + c:\filename.obj
Declare the prototype of function in the header file.
To include it in a program use syntax : #include c:\\filename.h.
Explain the automatic and static storage classes.
Automatic and static storage classes for variables defined uses memory as the storage.
These classes are local to the block in which variables are defined.
Automatic class uses the garbage value as the default initial value.
Static class uses the default initial value as zero.
These classes remain till the control remains within block in which the variable is defined.


Advanced C interview questions - senior level C interview

Explain the features of variables defined in the register storage class.
What is a macro?
Differentiate between the macros and the functions.
How can one file be included in another file?
What is #undef ?
Explain the # pragma directive.
List some of the escape sequences used in the c language.
Which structure is used to link the program and the operating system ?
What are command line arguments.
What are the limitations of scanf and how can it be avoided?
Explain the features of variables defined in the register storage class.
The data is stored in the CPU registers.
Default initial value taken by the variable defined in this class is garbage value.
It is local to the block in which the variable is defined.
The function is active till the control remains within the block in which variable is defined.
The value stored in this register is always accessed at a faster rate than value stored in memory.
Example: loop counters.
What is a macro?
It is a preprocessor directive used to change the value of constant at all places in a program by changing the
directive.
It uses the #define directive to define the value of constant before the main program.
The macro templates are always named in capital letters.
Example: #define UPPER 25
main( )
{
int a=0;
a = a+ UPPER;
}
Here the variable UPPER is defined and is assigned value 25.
UPPER is the macro template and 25 is its expansion and this 25 can be changed easily.
Differentiate between the macros and the functions.
Macro call replaces the templates with the expansion in a literal way.
Macro call makes the program run faster but also increases the program size.
Macro is simple and avoids errors related to the function calls.
In function call control is transferred to the function along with arguments.
It makes the functions small and compact.
Passing arguments and getting back the returned value takes time and makes the program run at slower rate.
How can one file be included in another file?
To include one file to another a preprocessor directive called file inclusion is used .
It causes the entire contents of filename to be inserted into the source code at that point in the program.
It is used when very large programs are present and the code is subdivided into different files containing the set of
related functions.
Syntax : #include filename or #include <filename>
Include search path in list of directories that would be searched for file being included.
What is #undef ?
Sometimes it is desirable to cause a defined name to become undefined so #undef is used.
It mainly undefine the macro which has been earlier #defined and represented as #undef macro template.
Example: #undef PENTIUM
This statement causes the definition of PENTIUM to be removed from the system.
Explain the # pragma directive.
This is a preprocessor directive that can be used to turn on or off certain features.
It is of two types #pragma startup, #pragma exit and pragma warn.
#pragma startup allows us to specify functions called upon program startup.
#pragma exit allows us to specify functions called upon program exit.
#pragma warn tells the computer to suppress any warning or not.
List some of the escape sequences used in the c language.
\t moves the curser to the next tab stop.
\b moves the curser one position to the left of its current position.
\r moves the curser to the beginning of the line in which it is currently placed.
\a alerts the user by sounding the speaker inside the computer.
\f is the form speed which advances the computer stationary attached to printer to top of next page.
Which structure is used to link the program and the operating system ?
The structure used to link the operating system to a program is file.
File is defined in the header file stdio.h(standard input/output header file).
It contains the information about file being used, its current size and its location in memory.
It contains character pointer that points to character that is being opened.
Opening a file establishes a link between the program and operating system about which file is to be accessed.
What are command line arguments.
The arguments that we pass on to main ( ) at the command prompt are called command line arguments.
It has two arguments called argc and argv.
argv is an array of pointers to string and argc is an int whose whole value is equal to number of strings to which agrv
points.
Here the address of first string is stored in the argv[0] and of second is stored in argv[1].
argc is set of number of strings given on command prompt.
What are the limitations of scanf and how can it be avoided?
scanf cannot work with the string of characters.
It is not possible to enter a multiword string into a single variable using scanf.
To avoid this the gets( ) function is used.
It gets a string from the keyboard and is terminated when enter key is pressed.
Here the spaces and tabs are acceptable as part of the input string.

Basic C interview questions - Frequently asked C interview

Give an example of escape sequence in c.
What is the difference between the 2 given statements?
What is conversion specification?
What is coercion?
Which function is used to input the values during execution of a program?
Is this statement valid or invalid?
Explain trailer technique.
Explain the ternary operators.
Point out the error in the expression a>b ? g=a : g=b;
Which statement is used to jump out of loop instantly?
Give an example of escape sequence in c.
Newline character is the example of escape sequence in c.
It is represented by symbol \n and is placed at the of control string.
It is composed of 2 characters but is translated by the compiler into single character.
It instructs the computer to move to the next line before the information is printed.
Example: printf(welcome to c \n) ;
What is the difference between the 2 given statements?
A) printf(The);
printf(rain);
B) printf(The\nrain);
A statement is printed as: Therain
It is so because no newline character is present between the and rain.
B statement is printed as : The
rain
Here the newline character is present between the words so rain shifts to the next line.
Here the number of lines displayed are determined by how many newline characters appear in the control string.
What is conversion specification?
Conversion specification is a composite symbol represented by %d.
Value of integer which appears in the printf statement is converted into decimal.
Here d represents the decimal value and the given integer is translated into integer.
Example : {
int hours= 24;
printf(There are %d hours in a day .\n, hours);
}
It prints : There are 24 hours in a day.
What is coercion?
It shows how the operands of different types are converted into mixed mode expression.
It is accomplished using cast operator.
The name of data type to be converted is enclosed in parentheses and placed to the left of value to be converted.

Example: int a= 7;
Float b= (float) a + 1.0
Here cast operator converts value of a to its equivalent float before addition of 1.0.
Which function is used to input the values during execution of a program?
The function scanf is used to input the values during execution of a program.
Scanf stands for scan function or scan formatting.
Syntax: scanf(%d, &n);
%d shows the data type of value entered and the value is stored in n.
It is used where a numeric value or character is to be read into simple variable.
if (c != d)
printf (c is not equal to d.\n);
d=c;
else
printf( c is equal to d.\n);
Is this statement valid or invalid?
This statement is invalid as a statement is present between if and else clause.
First statement is part of if clause and second statement is part of else clause.
Here the assignment statement belongs neither to if nor to else clause.
The syntax of if-else statement is
if ( expression)
statement1;
else (expression)
statement 2;
Explain trailer technique.
It is the special end of data value that trails all the meaning data.
Here a suitable condition is used that terminate the loop when condition is false.
One way is to choose a number that the user would never ask program to process.
Example: if program requires that user type in a radius, then entering negative number may be the way to terminate
the process.
Here ways are provided to terminate the loop in use.
Explain the ternary operators.
The conditional operators ? and : are called as the ternary operators.
These operators take three arguments .
They form the if then else statements and use a particular syntax.
Syntax: expression 1? expression 2: expression 3.
If expression 1 is true then value returned is expression 2.
Otherwise the value returned is expression 3.
Point out the error in the expression a>b ? g=a : g=b;
This expression give an error L valued required.
The error can be overcome by enclosing the statement in the : part within parenthesis.
Correct expression is a>b ? g=a : (g=b);
In absence of parenthesis the compiler considers that b is being assigned to expression to the left of =.
This is the limitation of conditional operator that only one C statement can occur after ? or: .
Which statement is used to jump out of loop instantly?
Keyword break is used to jump out of loop without waiting for conditional test.
After break statement the control automatically passes to the first statement after the loop.
It breaks the control only from the loop in which it is placed.
Example: if(32 /2 ==0)
{
printf(number is even);
break;
}

In the given example condition is true, so break statement occurs and control jumps out of the loop.

C interview questions and answers part 3

Part 1 Part 2 Part 3 Part 4 Part 5 Part 6 Part 7 Part 8 Part
9 Part 10 Part 11 Part 12 Part 13 Part 14 Part 15 Part 16 Part 17 Part 18 Part 19 Part 20 Part 21
What do you think about the following?
int i;
scanf("%d", i);
printf("%d", i);

- The program will compile without any errors.
- When you try to enter a value using "stdin", the system will try to store the value at location with address "i". "i" might
be invalid leading the program to crash and core dump.
- It implies that this code has a bug.
What will be the output of the following?
int main()

main();
return 0;

- Runt time error. Stack overflow.
What are the advantages os using linked list for tree construction?
- Unless the memory is full, overflow will never occur.
- Insertions & deletions are easier in comparison to arrays.
- Moving pointer is faster & easier in comparison to moving items when records are large.
Which data structure is used to perform recursion?
- Stack data structure is used to perform recursion.
- Its LIFO property stores return addresses of the 'caller' and its successions in recursion to find where the execution
control should return.
Explain the following.
a.) Queue -
- Queue is a FIFO or LIFO data structure.
- It permits two operations - enqueue & dequeue.
- The methods used to check the status of the queue are - empty() and full()

b.) Priority Queues -
- List of items with priority associated with it.
- Priority queues effectively support finding the item with highest priority across a series of operations.
- Basic priority queue operations are - insert, find maximum or minimum, delete maximum or minimum.
Explain the following.
a. ) Binary height balanced tree-
- It is a binary tree in which for every node the heights of left and right subtree differ by not more than 1.

b.) Ternary tree -
- In this tree a node can have zero or more child nodes.

c.) Red-black trees -
It is a binary search tree with following propoerties:
- Root is black.
- Every leaf is black.
- Every node is either red or black.
- For a red red node, both its children are black.
- All internal nodes have two children .
- Every simple path from node to a descendant leaf contains the same no. of black nodes.
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 which 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 programs that
generate undefined behavior which C language no longer specifies what can happen.


Throw some light on the following.
a.) Splay trees -
- These are self adjusting binary search trees.
- They can adjust optimally to any sequence of tree operations.
- Evertime a node of the tree is accessed, a radical surgery is performed on it. This results into
the newly accessed node turning into the root of the modified tree.
- Splaying steps used are: Zig rotation, Zag rotation, Zig-zag, Zag-zig, Zig-zig, Zag-zag.

b.) B tree -
- The root is either a tree leaf or has atleast two children.
- Each node (except root & tree leaves) has between ceil(m/2) and m children. Ceil being the
ceiling function.
- Each path from root to tree leaf has same length.
Explain -
a.) Threaded binary trees -
- Every node without a right child has a link(thread) to its INORDER successor.
- This threading avoids the recursive method of traversing a tree which makes stacks &
consumes a lot of memory & time.

b.) B+ tree -
- Consists of root, internal nodes and leaves.
- Root may be a leaf or internal node with two or more children.
- For a B+ tree of order v, internal nodes contain between v and 2v keys. A node with 'k' keys has
'k+1' children.
- Leaves exist on same level. They are the only nodes with data pointers.
Differentiate between full, complete & perfect binary trees.
- Full binary tree - Each node is either a leaf or internal node with exactly two non-empty
children.
- Complete binary tree - For a tree with height 'a', every level is completely filled, except
possibly the deepest one. At depth 'a', all nodes must be as far left as possible.
- Perfect binary tree - For a tree with height 'd', every internal node has two children and all the
leaf nodes exist at same level.
Explain the use of keyword 'register' with respect to variables.
- It specifies that variable is to be stored in a CPU register.
- 'register' keyword for variables and parameters reduces code size.
- The no. of CPU registers is dependent on its architectural design. Mostly this number is 32.
Define recursion in C.
A programming technique in which a function may call itself. Recursive programming is
especially well-suited to parsing nested markup structures
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 interview questions and answers part 5

Part 1 Part 2 Part 3 Part 4 Part 5 Part 6 Part 7 Part 8 Part
9 Part 10 Part 11 Part 12 Part 13 Part 14 Part 15 Part 16 Part 17 Part 18 Part 19 Part 20 Part 21
Explain #pragma statements.
- Implementations of C & C++ supports features unique to the OS or host machine.
- #pragma directives offer a way for each compiler to offer machine and OS specific features while retaining overall
compatibility.
- Pragmas are used in conditional statements, to provide new pre-processor functionality or implementation-defused
information to the compiler.
Explain the properties of union. What is the size of a union variable?
- With Union same storage can be referenced in different ways. What is the purpose of Trigraphs in
C?
Trigraphs are used as a sequence of three ISO characters. These characters are treated as one in the C alphabet.
The trigraphs start with the ?? (Question mark) it helps indicate that there is nothing important proceedings. The C
character trigraph is as follows:
#
??=
[
??(
]
??)
{
??<
}
??>
Trigraphs allow writing the possible symbols that are not possible without it. For example:
#define MAX can't be written on the terminal so there is a usage for the trigraph notation that makes it possible for the
user to write the code. It can be written as:
??=define MAX
Trigraphs make the coding more portable and gives more flexibility to the user to use it in case user moving from one
system to another. These are the first thing that has to be performed by the input text.
What is the translation phases used in C language?
There are various translation phases that can be used in C language. These are as follows:
a) The first stage of the translation phase is to check the trigraph and allow it to be used with the system.
b) The second stage is to do the identify the type of program that has to be written for that, the identification of
identifiers and others are figured out.
c) The third stage is the important stage where the translation from comments to the space takes place. The space is
not being seen in the case of strings or character constant. And multiple white spaces may be combined in one.
d) The last stage involves the complete translation of the program.
What are the different types of objects used in C?
There are two types of objects that are used in C and they are as follows: Internal object: deals with the internal
functionality of the program. Any function that is being defined inside is an internal function. Internal objects are used
inside the program itself and dont include any external references. External object: deals with the external functions
used in the program. All the functions are used as external as they can't be defined inside one another. The C
program is always a collection of external objects. The external objects are used for reducing the code and increasing
the usability of it. These objects gets involved in the cross-file and library communication.
What is the use of linkage in C language?
Linkage is the term that is used to describe the accessibility of the objects from one file to another file. This file can be
either from the same file or different files. The linkage is really helpful in managing large number of links when lots of
files are linked together with one another. User can declare the same function more than once within the same scope
or different scope. The packaging of the library function can be declared to the function in the header as its function is
defined in a source file. The source file is included in the header file as:
// first.c #include "first.h" int first(int n)
{

...

}
This way there is a surety that the function is defined in the source file and working with the same declarations as it is
mentioned in the above files. As it can be seen in here the declaration is done twice. And the second declaration also
consisted of the function as well as the definition. The linkage provides a way for the functions to be used in the same
scope.
What are the different types of linkage exist in C?
There are three types of linkages that are used to make an object accessible from one file to another. The linkages
that are being provided are as follows:
a) No linkage: defines the linkage that is having internal functionality and internal functions with its arguments and
variables internal to the application itself.
b) External linkage: external linkage defines the linkage that is located externally of the program. It is considered as
the default linkage for the functions and other parameters that are defined outside the scope of the program. All the
instances are refereed as the same object if they are preceded with the external linkage. For example printf() is
declared externally in <stdio.h> as int printf(const char *, ) this is the function that returns an integer.
c) Internal linkage: deals with the names that are internal to the files or the same objects within the same file. This
allows the user to define the linkage internally without shifting to many other files for the references. The internal
linkage can be done by prefixing the keyword static in front of the object name.
The following sample code will explain the linkages used:
// this is the second file that includes the first file externally
extern int i;
void f ()
{
// Write your own code here
i++;
}


What is the purpose of Trigraphs in C?
Trigraphs are used as a sequence of three ISO characters. These characters are treated as one in the C alphabet.
The trigraphs start with the ?? (Question mark) it helps indicate that there is nothing important proceedings. The C
character trigraph is as follows:
#
??=
[
??(
]
??)
{
??<
}
??>
Trigraphs allow writing the possible symbols that are not possible without it. For example:
#define MAX can't be written on the terminal so there is a usage for the trigraph notation that makes it possible for the
user to write the code. It can be written as:
??=define MAX
Trigraphs make the coding more portable and gives more flexibility to the user to use it in case user moving from one
system to another. These are the first thing that has to be performed by the input text.
What is the translation phases used in C language?
There are various translation phases that can be used in C language. These are as follows:
a) The first stage of the translation phase is to check the trigraph and allow it to be used with the system.
b) The second stage is to do the identify the type of program that has to be written for that, the identification of
identifiers and others are figured out.
c) The third stage is the important stage where the translation from comments to the space takes place. The space is
not being seen in the case of strings or character constant. And multiple white spaces may be combined in one.
d) The last stage involves the complete translation of the program.
What are the different types of objects used in C?
There are two types of objects that are used in C and they are as follows: Internal object: deals with the internal
functionality of the program. Any function that is being defined inside is an internal function. Internal objects are used
inside the program itself and dont include any external references. External object: deals with the external functions
used in the program. All the functions are used as external as they can't be defined inside one another. The C
program is always a collection of external objects. The external objects are used for reducing the code and increasing
the usability of it. These objects gets involved in the cross-file and library communication.
What is the use of linkage in C language?
Linkage is the term that is used to describe the accessibility of the objects from one file to another file. This file can be
either from the same file or different files. The linkage is really helpful in managing large number of links when lots of
files are linked together with one another. User can declare the same function more than once within the same scope
or different scope. The packaging of the library function can be declared to the function in the header as its function is
defined in a source file. The source file is included in the header file as:
// first.c #include "first.h" int first(int n)
{

...

}
This way there is a surety that the function is defined in the source file and working with the same declarations as it is
mentioned in the above files. As it can be seen in here the declaration is done twice. And the second declaration also
consisted of the function as well as the definition. The linkage provides a way for the functions to be used in the same
scope.
What are the different types of linkage exist in C?
There are three types of linkages that are used to make an object accessible from one file to another. The linkages
that are being provided are as follows:
a) No linkage: defines the linkage that is having internal functionality and internal functions with its arguments and
variables internal to the application itself.
b) External linkage: external linkage defines the linkage that is located externally of the program. It is considered as
the default linkage for the functions and other parameters that are defined outside the scope of the program. All the
instances are refereed as the same object if they are preceded with the external linkage. For example printf() is
declared externally in <stdio.h> as int printf(const char *, ) this is the function that returns an integer.
c) Internal linkage: deals with the names that are internal to the files or the same objects within the same file. This
allows the user to define the linkage internally without shifting to many other files for the references. The internal
linkage can be done by prefixing the keyword static in front of the object name.
The following sample code will explain the linkages used:
// this is the second file that includes the first file externally
extern int i;
void f ()
{
// Write your own code here
i++;
}

- When sizeof is applied to a union it shows the size of biggest member.
- Each initialization of union over-writes the previous one - there's no standard way.
- Syntax, format and use of tags and decorators are like struct, but members overlay each other, rather than following
each other in memory.
What is the format specifier for printing a pointer value?
- %p format specifier displays the corresponding arguement that is a pointer.
- %x can be used to print a value in hexadecimal format. not be performed on void
Why can arithmetic operations pointers?
- We don't know the size of what's being pointed to with a void *. So, it is difficult to determine how far to seek the
pointer to get the next valid address.
What are bitwise shift operators?
<< - Bitwise Left-Shift
Bitwise Left-Shift is useful when to want to MULTIPLY an integer (not floating point numbers) by a power of 2.
Expression: a << 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.


Write a program to show the change in position of a cursor using C
The program that can be made to show the changes in position of a cursor using C includes the libraries that are on
the graphics level like <dos.h>. This way the cursor representation can be shown graphically to the user. The
program of doing that is as follows:
int main()
{
union REGS, n, i;
n.h.b=2; //It is used to position the cursor
n.h.c=0;
n.h.c=40;
n.h.c=50;
int86(0x10,&n,&i);
printf(This will show the positioning of the cursor);
return 0;
}
What is the function of pragma directive in C?
Pragma is a directive with different implementation rules and use. There are many directives that vary from one
compiler to another compiler. The pragma directive is used to control the actions of the compiler that is ignored during
the preprocessing. It passes the instructions to the compiler to perform various actions without affecting the program
as whole. The syntax is as follows:
pragma-string passes the instructions to the compiler with some of the required parameters. The parameters are as
follows:
Copyright- it specifies the copyright string.
Copyright_date- it specifies the copyright date for the copyright string. Some version control can be given as
parameter.
The sample code that is being given as:
#pragma pragma-string.
#include<stdio.h>
#pragma pragma-string
int main(){
printf("C is powerful language ");
return 0;
}
What is the data segment that is followed by C?
The data segment is the segment that consists of the four parts:
a) Stack area: it is the first segment part that consists of all the automatic variables and constants that are stored in
the stack area. The automatic variables that are included in C are the local variables that are of default storage class,
variable of auto class, integer, character, string constants, etc., function parameters and return values.
b) Data area: that consists of all the extern and static variables that are stored in this area. It stores the data
permanently the memory variables that are initialized and not initialized.
c) Heap area: that consists of the memory that can be allocated dynamically to the processes. The memory can be
dynamically allocated by the use of the function malloc() and calloc().
d) Code area: that consists of a function pointer that is used to access only the code area. The size of the area
remains fixed and it remains in the read only memory area.
What is the function of multilevel pointer in c?
Multilevel pointer is a pointer that points to another pointer in a series. There can be many levels to represent the
pointers. The multilevel pointers are given as:
#include<stdio.h>
int main(){
int s=2,*r=&s,**q=&r,***p=&q;
printf("%d",p[0][0][0]);
return 0;
}
In the above code the ***p will be pointing to the pointer of pointer that is **q and **q in case will be pointing to
another pointer that is s. This chain will continue if new addition will take place.
What is use of integral promotions in C?
Integral promotions deals with the promotions that are internally being performed to convert the lower precision level
to higher level like shorter to int. The conversations that is being defined includes: A short or char will be converted to
the int automatically. If the assignment is not being done then the conversation will be assigned to the unsigned int.
Through this the original value and sign can be preserved for further actions. The conversation of char can be treated
as signed or unsigned but it will always been implementation dependent. These are helpful in applying a conversation
on which sift, unary +, -, and ~ operators can be taken place.
What is the use of ?: operator?
This ?: operator is used to show the conditional statement that allows the output of the statement to be either true or
false. This operator is used as:
expression?expression1:expression2
If the expression is true then the result will be expression1. If the expression is false then the result will be
expression3. There is only one evaluation take place for the result. The expression that is used with arithmetic
operators are easy to solve and it is easy to convert and apply to the expressions.
What is the condition that is applied with ?: operator?
The condition that has to be applied with the ?: operator is as follows:
The type of the result will be generated if there are two operands of compatible types. The pointers can be mixed
together to give some result. The pointers that are involved for the result has two steps to follow:
a) If an operand is a pointer then the result will be of a pointer type.
b) If any of the operand is a null pointer constant then result will be considered of the operand. The example is shown
below:
#include <stdio.h>
#include <stdlib.h>
main(){
int i;
for(i=0; i <= 10; i++){
printf((i&1) ? "odd\n" : "even\n");
}
exit(EXIT_SUCCESS);
What is the function of volatile in C language?
Volatile is a keyword that is used with the variables and objects. It consists of the special properties that are related to
the optimization and threading. It doesn't allow the compiler to apply the customization on the source code for the
values that can't be changed automatically. It allows the access to the memory devices that are mapped to the
particular function or the keyword. It also allows the use of variables that is between the function setjmp and longjmp.
It handles the signals that are passed for the variables. The operations on the variables are not atomic and they are
made before any relationship of the threading occurs.
What is the use of void pointer and null pointer in C language?
Void pointer: is a type of pointer that points to a value that is having no type. It points to any of the data type. It is
used to take the type automatically on run time and it is used to change from integer or float to string of characters. It
allows passing null pointer.
Null pointer: null pointer is just used as a regular pointer that consists of any pointer type with some special value. It
doesn't point to any valid reference or memory address. It is just used for easy to make a pointer free. The resul t is
the result of the type-casting where the integer value can have any pointer type.
What is the process of writing the null pointer?
The null pointer can be written either by having an integral constant with a value of 0 or this value can be converted to
void* type. This can be done by using the cast function. For assigning any pointer type to any other pointer type then
it first gets converted to other pointer type and then will appear in the program. The code that is being written for null
pointer is:
int *ip;
ip = (int *)6;
*ip = 0xFF;
What are the different properties of variable number of arguments?
The properties of variable number of arguments are as follows:
The first parameter of the argument should be of any data type. The invalid
Declaration of a function will be done like
int(a);
The valid declaration of the function will be like:
int(char c);
void(int,float);
There should not be any passing from one data type to another data type. There is also invalid declaration on the
basis of:
int(int a,int b);
There should not be any blank spaces in between the two periods. The placing of any other data type can be done in
place of ellipsis.
How does normalization of huge pointer works?
Huge pointer is the pointer that can point to the whole memory of the RAM and that can access all the segments that
are present in a program. The normalization can be done depending on the microprocessor of the system. The
physical memory of the system is represented in 20 bit and then there is a conversion of 4 byte or 32 bit address. The
increment of the huge pointer will also affect the offset and segment address. Through the huge pointer the access
and modification of device driver memory, video memory, etc. Huge pointer manages the overall system of the
memory model and also normalizes the overall use of the pointers.
What are the different types of pointers used in C language?
There are three types of pointers used in C language. These pointers are based on the old system architecture. The
types are as follows:
a) Near pointer: this is the pointer that points only to the data segment. There is a restriction of using it beyond the
data segment. The near pointer can be made by using the keyword as near.
b) Far pointer: it will access the total memory of the system and can be use to point to every object used in the
memory.
c) Wild pointer: it is a pointer that is not being initialized.
What is the difference between null pointer and wild pointer?
Wild pointer is used to point to the object but it is not in initialization phase. Null pointer points to the base address of
a particular segment. Wild pointer consists of the addresses that are out of scope whereas null pointer consists of the
addresses that are accessible and in the scope. Wild pointer is declared and used in local scope of the segment
whereas null is used in the full scope.
What is the function of dangling pointer?
Dangling pointer is used as a wild pointer only that is pointing to the memory address of the variable that is been
deleted from memory location. Dangling pointer points to a memory location still even the pointer is being removed
from the segment. When an object is deleted or deallocated then the problem of dangling pointer arises. In this
condition if the user tries to reallocate the freed memory to another process then the original program gives different
behavior from the one it is expected from the program.

C interview questions and answers part 10

Part 1 Part 2 Part 3 Part 4 Part 5 Part 6 Part 7 Part 8 Part
9 Part 10 Part 11 Part 12 Part 13 Part 14 Part 15 Part 16 Part 17 Part 18 Part 19 Part 20 Part 21
Differentiate between: a.) Declaring a variable b.) Defining a variable
a.) Declaring a variable - Declaration informs the compiler about size and type of variable at the time of compilation.
No space is reserved in the memory as a result of declaring the variables.
b.) Defining a variable - means declaring it and reserving a place for it in the memory.
Defining a variable = Declaration + Space reservation.
Where are auto variables stored? What are the characteristics of an auto variable?
Auto variables are defined under automatic storage class. They are stored in main memory.
- Main memory
- CPU registers
Memory is allocated to an automatic variable when the block containing it is called. When the block execution is
completed, it is de-allocated.
Characteristic of auto variables:
- Stored in: main memory
- Default value: garbage
- Scope: Local to the block where it is defined
- Life: Till the control stays in the block where it is defined
Why do we use namespace feature?
- Multiple library providers might use common global identifiers. This can cause name collision when an application
tries to link with two or more such libraries.
- The namespace feature surrounds a library's external declarations with a unique namespace that eliminates the
potential for those collisions.
namespace [identifier] { namespace-body }
- A namespace declaration identifies and assigns a name to a declarative region.
- The identifier in a namespace declaration must be unique in the declarative region in which it is used.
- The identifier is the name of the namespace and is used to reference its members.
How are structure passing and returning implemented?
- When structures are passed as arguments to functions - the whole structure is usually pushed on the stack, through
as several words as are needed.
- In order to avoid this overhead, usually pointers to structures are used.
- Some compilers simply pass a pointer to the structure, even though they have to produce a local copy to save pass-
by-value semantics.
- Structures are usually returned from functions in a position pointed to by an additional, compiler-supplied hidden
argument to the function.
- Some old compilers used to use unique, static locations for structure returns.


C interview questions and answers part 11

Part 1 Part 2 Part 3 Part 4 Part 5 Part 6 Part 7 Part 8 Part
9 Part 10 Part 11 Part 12 Part 13 Part 14 Part 15 Part 16 Part 17 Part 18 Part 19 Part 20 Part 21
Why cant we compare structures?
- A way for a compiler to apply structure evaluation that is constant with lower level flavor of C does not exist.
- A plain byte-by-bye comparison could be found on random bits available in unused holes in the structure.
- This filling maintains the arrangement of following fields accurate.
- A field-by-field assessment may require improper amounts of recurring code for larger structures.
What do you mean by invalid pointer arithmetic?
Invalid pointer arithmetic include:
(i) Adding, dividing and multiplying two pointers
(ii) Adding double or float to pointer
(iii) Masking or shifting pointer
(iv) Assigning a pointer of one type to another type of pointer.
What is the purpose of ftell?
- ftell() function is used to get the current file referred by the file pointer.
- ftell(fp); returns a long integer value referring the current location of the file pointed by the file pointer fp.
- If there's an error, it will return -1.
Explain a pre-processor and its advantages.
Pre-processor practices the source code program before it is sent through the compiler.
(i) It increases the readability of a program and enables implementing comprehensive program.
(ii) It helps in easier modification
(iii) It facilitates writing convenient programs
(iv) It helps in easier debugging and testing a portion of the program
What do the c and v in argc and argv stand for?
- The c in argument count, argc stands for the number of the command line argument that the program is invoked
with.
- And v in argument vector, argv is a pointer to an array of the character string that contains the argument.


C interview questions and answers part 12

Part 1 Part 2 Part 3 Part 4 Part 5 Part 6 Part 7 Part 8 Part
9 Part 10 Part 11 Part 12 Part 13 Part 14 Part 15 Part 16 Part 17 Part 18 Part 19 Part 20 Part 21
How can we read/write Structures from/to data files?
- In order to compose a structure fwrite() can be used as Fwrite(&e, sizeof(e),1,fp). e refers to a structure variable.
- A consequent fread() invocation will help in reading the structure back from file.
- Calling function fwrite() will write out sizeof(e) byte from the address & e.
- Data files that are written as memory images with function fwrite() will not be portable, especially if they include
floating point fields or pointers.
- This happens because structures memory layout is compiler and machine dependent.
Differentiate between ordinary variable and pointer in C.
Ordinary variable - It is like a container which can hold any value. Its value can be changed anytime during the
program.
Pointer - Stores the address of the variable.
Explain "far" and "near" pointers in C.
- "Far" and "Near" - non-standard qualifiers avilable in x86 systems only.
- Near pointer - Refers to an address in known segment only.
- Far pointer - Compound value containing a segment number and offset into that segment
When should you use a type cast?
Type cast should be used in two cases:
a.) To change the type of an operand to an arithmetic operation so that the operation can be performed properly.
b.) To cast pointer types to and from void *, to interface with functions that return void pointers.
What are storage classes in C?
a.) Automatic storage classes : Variable with block scope but without static specifier.
b.)
C interview questions and answers part 13

Part 1 Part 2 Part 3 Part 4 Part 5 Part 6 Part 7 Part 8 Part
9 Part 10 Part 11 Part 12 Part 13 Part 14 Part 15 Part 16 Part 17 Part 18 Part 19 Part 20 Part 21
Explain null pointer.
Null pointer - A pointer that doesn't point to anything.
It is used in three ways:
- To stop indirection in a recursive data structure.
- As an error value
- As a sentinel value
How do you initialize pointer variables?
Pointer variables are initialized in two ways:
- By static memory allocation
- By dynamic memory allocation
What is an lvalue?
- lvalue - an expression to which a value can be assigned.
- It is located on the left side of an assignment statement
- lvalue expression must reference a storable variable in memory.
- It is not a constant.
What are the advantages and disadvantages of external class?
Advantages of external storage class:
- Retains the latest value with persistent storage.
- The value is available globally.
Disadvantages of external storage class:
- Storage for external variable exists even when it is not needed.
- Modification of the programme becomes difficult.
- It affects the generality of the programme.
When should you not use a type cast?
- You should not use type cast to override a constant or volatile declaration as it can cause the failure of effective
running of program.
- It should not be used to turn a pointer to one type of structure or data type into another.
c.)
b.) Static storage classes: Variables with block scope and with static specifier. Global variables with or
without static specifier.
d.)
e.)
c.) Allocated storage classes: Memory obtained from calls to malloc(), alloc() or realloc().


w questions and answers part 14

Part 1 Part 2 Part 3 Part 4 Part 5 Part 6 Part 7 Part 8 Part
9 Part 10 Part 11 Part 12 Part 13 Part 14 Part 15 Part 16 Part 17 Part 18 Part 19 Part 20 Part 21
Explain modulus operator. What are the restrictions of a modulus operator?
- Modulus operator - provides the remainder value.
- It is applied to integral operands.
- It can not be applied to float or double.
21. Explain: a.) Function b.) Built-in function
a.) Function
- When a large program is divided into smaller subprograms - each subprogram specifying the actions to be
performed - these subprograms are called functions.
- Function supports only static and extern storage classes.
b.) Built-in function
- Predefined functions supplied along with the compiler.
- They are also called library functions.
Explain: a.) goto b.) setjmp()
a.) goto - statement implements a local jump of program execution. This statement bypasses the code in your
program and jumps to a predefined position. You need to provide the program a labelled position to jump to. This
position has to be within the same function. It is not possible to implement goto between different functions.
b.) setjmp() - implement a non local, far jump of program execution. This function can be implemented between
different functions. When setjmp() is used, the current state of the program is saved in a structure of type jmp_buf.
Using goto and setjmp() is not a good programming practice. They cause a wastage of memory leading to a largely
reduction in the efficiency of the program.
What do you mean by Enumeration Constant?
- Enumeration is a data type. Using enumeration constant, it is possible to create your own data type and define the
values it can take.
- This helps in increasing the readability of the program.
Enum is declared in two parts:
a.) Part one declares the data types and specifies the possible values called enumerators.
b.) Part two declares the variables of this data type.
Explain Union. What are its advantages?
- Union - collection of different types of data items.
- Though it has members of different data types, at a time it can hold data of only one member.
- Same memory is allocated to teo members of different data types in a Union. The memory allocated is equal to the
maximum size of members.
- The data is interpreted in bytes depending on the member accessed.
- Union is efficient when its members are not required to be accessed at the same time.


C interview questions and answers part 15

Part 1 Part 2 Part 3 Part 4 Part 5 Part 6 Part 7 Part 8 Part
9 Part 10 Part 11 Part 12 Part 13 Part 14 Part 15 Part 16 Part 17 Part 18 Part 19 Part 20 Part 21
What is the purpose of main() function?
- Execution starts from main() in C
- It can contain any number of statements
- Statements are executed in the sequence in which they are written
- It can call other functions. The control is passed to that function.
E.g. int main();
OR
int main(int argc, char *argv[]);
Explain argument and its types.
Argument : An expression which is passed to a function by its caller for the function to perform its task.
Arguments are of two types: actual and formal.
- Actual argument: These are the arguments passed in a function call. They are defined in the calling function.
- Formal argument: Formal arguments are the parameters in a function declaration. Their scope is local to the
function definition. They belong to the function being called and are a copy of actual arguments. Change in formal
argument doesn't get reflected in actual argument.
Which of these functions is safer to use : fgets(), gets()? Why?
- Out of the two fgets() is safer.
- gets() receives the string from the keyboard and stops when the "enter" key is hit
- There is no limit to the size of the string which can cause memory over flow.
What are pointers? Why are they used?
Pointers are variables which store the address of other variables.
Adavantages of using pointers:
- They allow to pass values to functions using call by reference - especially useful while large sized arrays are passed
as arguements to functions.
- They allow dynamic allocation of memory.
- They help in resizing the data structures.

Vous aimerez peut-être aussi