Question
1. Explain The Purpose Of Main( ) Function?
Answer
:
The function main( )
invokes other functions within it.It is the first function to be called when
the program starts execution.
It
is the starting function.
It
returns an int value to the environment that called the program.
Recursive
call is allowed for main( ) also.
It
is a user-defined function.
Program
execution ends when the closing brace of the function main( ) is reached.
It has two arguments argument count and.
argument vector (represents strings passed).
Any
user-defined name can also be used as parameters for main( ) instead of argc
and argv.
Question
2. Write The Equivalent Expression For X%8?
Answer
:
x&7.
Question
3. Why N++ Executes Faster Than N+1?
Answer
:
The expression n++
requires a single machine instruction such as INR to carry out the increment
operation whereas n+1 requires more instructions to carry out this operation.
Question
4. Can The Sizeof Operator Be Used To Tell The Size Of An Array Passed To A
Function?
Answer
:
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.
Question
5. Is Using Exit () The Same As Using Return?
Answer
:
No. The exit () function
is used to exit your program and return control to the operating system. The
return statement is used to return from a function and return control to the
calling function. If you issue a return from the main () function, you are
essentially returning control to the calling function, which is the operating
system. In this case, the return statement and exit () function are similar.
Question
6. What Is A Function And Built-in Function?
Answer
:
A large program is
subdivided into a number of smaller programs or subprograms. Each subprogram
specifies one or more actions to be performed for a large program. Such
subprograms are functions. The function supports only static and extern storage
classes. By default, function assumes extern storage class. Functions have
global scope. Only register or auto storage class is allowed in the function
parameters. Built-in functions that predefined and supplied along with the compiler
are known as built-in functions. They are also known as library functions.
Question
7. Write About Modular Programming?
Answer
:
If a program is large,
it is subdivided into a number of smaller programs that are called modules or
subprograms. If a complex problem is solved using more modules, this approach
is known as modular programming.
Question
8. When Does The Compiler Not Implicitly Generate The Address Of The First
Element Of An Array?
Answer
:
Whenever an array name
appears in an expression such as,
array
as an operand of the sizeof operator.
array
as an operand of & operator.
array
as a string literal initializer for a character array.
Then the compiler does
not implicitly generate the address of the address of the first element of an
array.
Question
9. Mention The Characteristics Of Arrays In C?
Answer
:
An
array holds elements that have the same data type.
Array
elements are stored in subsequent memory locations.
Two-dimensional
array elements are stored row by row in subsequent memory locations.
Array
name represents the address of the starting element.
Array
size should be mentioned in the declaration. Array size must be a constant
expression and not a variable.
Question
10. Differentiate Between A Linker And Linkage?
Answer
:
A linker converts an
object code into an executable code by linking together the necessary build in
functions. The form and place of declaration where the variable is declared in
a program determine the linkage of variable.
Question
11. What Are The Advantages Of Auto Variables?
Answer
:
The
same auto variable name can be used in different blocks.
There
is no side effect by changing the values in the blocks.
The
memory is economically used.
Auto
variables have inherent protection because of local scope.
Question
12. What Is Storage Class And What Are Storage Variable?
Answer
:
A storage class is an
attribute that changes the behavior of a variable. It controls the lifetime,
scope and linkage. There are five types of storage classes.
auto.
static.
extern.
register.
typedef.
Question
13. Which Expression Always Return True? Which Always Return False?
Answer
:
expression
if (a=0) always return false.
expression
if (a=1) always return true.
Question
14. Is It Possible To Execute Code Even After The Program Exits The Main ()
Function?
Answer
:
The standard C library
provides a function named at exit () that can be used to perform “cleanup”
operations when your program terminates. You can set up a set of functions you
want to perform automatically when your program exits by passing function
pointers to the at exit() function.
Question
15. Why Should I Prototype A Function?
Answer
:
A function prototype
tells the compiler what kind of arguments a function is looking to receive and
what kind of return value a function is going to give back. This approach helps
the compiler ensure that calls to a function are made correctly and that no
erroneous type conversions are taking place.
Question
16. How Do You Print An Address?
Answer
:
The safest way is to use
printf () (or fprintf() or sprintf()) with the %P specification. That prints a
void pointer (void*). Different compilers might print a pointer with different
formats. Your compiler will pick a format that’s right for your environment.
If you have some other
kind of pointer (not a void*) and you want to be very safe, cast the pointer to
a void*:
printf (“%Pn”, (void*) buffer);
Question
17. Can Math Operations Be Performed On A Void Pointer?
Answer
:
No. Pointer addition and
subtraction are based on advancing the pointer by a number of elements. By
definition, if you have a void pointer, you don’t know what it’s pointing to,
so you don’t know the size of what it’s pointing to. If you want pointer
arithmetic to work on raw addresses, use character pointers.
Question
18. How Can You Determine The Size Of An Allocated Portion Of Memory?
Answer
:
You can’t, really free()
can , but there’s no way for your program to know the trick free() uses. Even
if you disassemble the library and discover the trick, there’s no guarantee the
trick won’t change with the next release of the compiler.
Question
19. What Is A "null Pointer Assignment" Error? What Are Bus Errors,
Memory Faults, And Core Dumps?
Answer
:
These are all serious
errors, symptoms of a wild pointer or subscript. Null pointer assignment is a
message you might get when an MS-DOS program finishes executing. Some such
programs can arrange for a small amount of memory to be available “where the NULL
pointer points to” (so to speak). If the program tries to write to that area,
it will overwrite the data put there by the compiler. When the program is done,
code generated by the compiler examines that area. If that data has been
changed, the compiler-generated code complains with null pointer assignment.
This message carries
only enough information to get you worried. There’s no way to tell, just from a
null pointer assignment message, what part of your program is responsible for
the error. Some debuggers, and some compilers, can give you more help in
finding the problem. Bus error: core dumped and Memory fault: core dumped are
messages you might see from a program running under UNIX. They’re more
programmers friendly. Both mean that a pointer or an array subscript was wildly
out of bounds. You can get these messages on a read or on a write. They aren’t
restricted to null pointer problems.
The core dumped part of
the message is telling you about a file, called core that has just been written
in your current directory. This is a dump of everything on the stack and in the
heap at the time the program was running. With the help of a debugger, you can
use the core dump to find where the bad pointer was used. That might not tell
you why the pointer was bad, but it’s a step in the right direction. If you
don’t have write permission in the current directory, you won’t get a core
file, or the core dumped message.
Question
20. What Is The Heap?
Answer
:
The heap is where
malloc(), calloc(), and realloc() get memory.
Getting memory from the
heap is much slower than getting it from the stack. On the other hand, the heap
is much more flexible than the stack. Memory can be allocated at any time and
deallocated in any order. Such memory isn’t deallocated automatically; you have
to call free ().
Recursive data
structures are almost always implemented with memory from the heap. Strings
often come from there too, especially strings that could be very long at
runtime. If you can keep data in a local variable (and allocate it from the
stack), your code will run faster than if you put the data on the heap.
Sometimes you can use a better algorithm if you use the heap—faster, or more
robust, or more flexible. It’s a tradeoff.
If memory is allocated
from the heap, it’s available until the program ends. That’s great if you
remember to deallocate it when you’re done. If you forget, it’s a problem. A
“memory leak” is some allocated memory that’s no longer needed but isn’t
deallocated. If you have a memory leak inside a loop, you can use up all the
memory on the heap and not be able to get any more. (When that happens, the allocation
functions return a null pointer.) In some environments, if a program doesn’t
deallocate everything it allocated, memory stays unavailable even after the
program ends.
Question
21. Difference Between Null And Nul?
Answer
:
NULL is a macro defined
in for the null pointer. NUL is the name of the first character in the
ASCII character set. It corresponds to a zero value. There’s no standard macro
NUL in C, but some people like to define it.
The digit 0 corresponds
to a value of 80, decimal. Don’t confuse the digit 0 with the value of ‘’
(NUL)!
NULL can be defined as
((void*)0), NUL as ‘ ’.
Question
22. What Is The Stack?
Answer
:
The stack is where all
the functions’ local (auto) variables are created. The stack also contains some
information used to call and return from functions.
A “stack trace” is a
list of which functions have been called, based on this information. When you
start using a debugger, one of the first things you should learn is how to get
a stack trace. The stack is very inflexible about allocating memory; everything
must be deallocated in exactly the reverse order it was allocated in. For
implementing function calls, that is all that’s needed. Allocating memory off
the stack is extremely efficient. One of the reasons C compilers generate such
good code is their heavy use of a simple stack.
There used to be a C
function that any programmer could use for allocating memory off the stack. The
memory was automatically deallocated when the calling function returned. This
was a dangerous function to call; it’s not available anymore.
Question
23. When Should A Far Pointer Be Used?
Answer
:
Sometimes you can get
away with using a small memory model in most of a given program. There might be
just a few things that don’t fit in your small data and code segments. When
that happens, you can use explicit far pointers and function declarations to
get at the rest of memory. A far function can be outside the 64KB segment most
functions are shoehorned into for a small-code model. (Often, libraries are
declared explicitly far, so they’ll work no matter what code model the program
uses.)
A far pointer can refer
to information outside the 64KB data segment. Typically, such pointers are used
with farmalloc () and such, to manage a heap separate from where all the rest
of the data lives. If you use a small-data, large-code model, you should
explicitly make your function pointers far.
Question
24. Differentiate Between Far And Near?
Answer
:
Some compilers for PC
compatibles use two types of pointers. Near pointers are 16 bits long and can
address a 64KB range. far pointers are 32 bits long and can address a 1MB
range.
Near pointers operate
within a 64KB segment. There’s one segment for function addresses and one
segment for data. far pointers have a 16-bit base (the segment address) and a
16-bit offset. The base is multiplied by 16, so a far pointer is effectively 20
bits long. Before you compile your code, you must tell the compiler which
memory model to use. If you use a small code memory model, near pointers are
used by default for function addresses.
That means that all the
functions need to fit in one 64KB segment. With a large-code model, the default
is to use far function addresses. You’ll get near pointers with a small data
model, and far pointers with a large data model. These are just the defaults;
you can declare variables and functions as explicitly near or far.
Far pointers are a
little slower. Whenever one is used, the code or data segment register needs to
be swapped out. Far pointers also have odd semantics for arithmetic and
comparison. For example, the two far pointers in the preceding example point to
the same address, but they would compare as different! If your program fits in
a small-data, small-code memory model, your life will be easier.
Question
25. Is It Better To Use Malloc () Or Calloc ()?
Answer
:
Both the malloc() and
the calloc() functions are used to allocate dynamic memory. Each operates
slightly different from the other. malloc() takes a size and returns a pointer
to a chunk of memory at least that big:
void *malloc( size_t size );
calloc() takes a number
of elements, and the size of each, and returns a pointer to a chunk of memory
at least big enough to hold them all:
void *calloc( size_t numElements,size_t
sizeOfElement );
There’s one major
difference and one minor difference between the two functions. The major
difference is that malloc () doesn’t initialize the allocated memory. The first
time malloc () gives you a particular chunk of memory, the memory might be full
of zeros. If memory has been allocated, freed, and reallocated, it probably has
whatever junk was left in it. That means, unfortunately, that a program might
run in simple cases (when memory is never reallocated) but break when used
harder (and when memory is reused). calloc() fills the allocated memory with
all zero bits. That means that anything there you’re going to use as a char or
an int of any length, signed or unsigned, is guaranteed to be zero. Anything
you’re going to use as a pointer is set to all zero bits. That’s usually a null
pointer, but it’s not guaranteed. Anything you’re going to use as a float or
double is set to all zero bits; that’s a floating-point zero on some types of
machines, but not on all.
The minor difference
between the two is that calloc () returns an array of objects; malloc ()
returns one object. Some people use calloc () to make clear that they want an
array.
Question
26. Why Is That We Have To Assign Null To The Elements (pointer) After Freeing
Them?
Answer
:
This is paranoia based
on long experience. After a pointer has been freed, you can no longer use the
pointed-to data. The pointer is said to “dangle”; it doesn’t point at anything
useful. If you “NULL out” or “zero out” a pointer immediately after freeing it,
your program can no longer get in trouble by using that pointer. True, you
might go indirect on the null pointer instead, but that’s something your
debugger might be able to help you with immediately. Also, there still might be
copies of the pointer that refer to the memory that has been deallocated;
that’s the nature of C. Zeroing out pointers after freeing them won’t solve all
problems.
Question
27. When Would You Use A Pointer To A Function?
Answer
:
Pointers to functions
are interesting when you pass them to other functions. A function that takes
function pointers says, in effect, “Part of what I do can be customized. Give
me a pointer to a function, and I’ll call it when that part of the job needs to
be done. That function can do its part for me.” This is known as a “callback.”
It’s used a lot in graphical user interface libraries, in which the style of a
display is built into the library but the contents of the display are part of
the application.
As a simpler example,
say you have an array of character pointers (char*s), and you want to sort it
by the value of the strings the character pointers point to. The standard
qsort() function uses function pointers to perform that task. qsort() takes
four arguments,
a
pointer to the beginning of the array,
the
number of elements in the array,
the
size of each array element, and,
a
comparison function, and returns an int.
Question
28. What Does It Mean When A Pointer Is Used In An If Statement?
Answer
:
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.
Question
29. Is Null Always Defined As 0?
Answer
:
NULL is defined as
either 0 or (void*)0. These values are almost identical; either a literal zero
or a void pointer is converted automatically to any kind of pointer, as
necessary, whenever a pointer is needed (although the compiler can’t always
tell when a pointer is needed).
Question
30. What Is A Null Pointer?
Answer
:
There are times when
it’s necessary to have a pointer that doesn’t point to anything. The macro
NULL, defined in , has a value that’s guaranteed to be different from any
valid pointer. NULL is a literal zero, possibly cast to void* or char*. Some
people, notably C++ programmers, prefer to use 0 rather than NULL. The null
pointer is used in three ways:
To
stop indirection in a recursive data structure
As
an error value
As
a sentinel value
Question
31. Mention The Levels Of Pointers Can You Have?
Answer
:
The answer depends on
what you mean by “levels of pointers.” If you mean “How many levels of
indirection can you have in a single declaration?” the answer is “At least 12.”
int i = 0;
int *ip01 = & i;
int **ip02 = & ip01;
int ***ip03 = & ip02;
int ****ip04 = & ip03;
int *****ip05 = & ip04;
int ******ip06 = & ip05;
int *******ip07 = & ip06;
int ********ip08 = & ip07;
int *********ip09 = & ip08;
int **********ip10 = & ip09;
int ***********ip11 = & ip10;
int ************ip12 = & ip11;
************ip12 = 1; /* i = 1 */
The ANSI C standard says
all compilers must handle at least 12 levels. Your compiler might support more.
Question
32. What Is Indirection?
Answer
: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.
Question
33. How Do You Print Only Part Of A String?
Answer
:
/* Use printf () to
print the first 11 characters of source_str. */
printf (“First 11 characters: ‘%11.11s’n”,
source_str);
Question
34. How To Convert A String To A Number?
Answer
:
The standard C library
provides several functions for converting strings to numbers of all formats
(integers, longs, floats, and so on) and vice versa.
The
following functions can be used to convert strings to numbers:
Function
Name Purpose
atof():
Converts a string to a double-precision floating-point value.
atoi():
Converts a string to an integer.
atol():
Converts a string to a long integer.
Question
35. How To Convert A Number To A String?
Answer
:
The
standard C library provides several functions for converting numbers of all
formats (integers, longs, floats, and so on) to strings and vice versa The
following functions can be used to convert integers to strings:
Function Name Purpose
iota():
Converts an integer value to a string.
ltoa
(): Converts a long integer value to a string.
ultoa
(): Converts an unsigned long integer value to a string.
The
following functions can be used to convert floating-point values to strings:
Function Name Purpose
ecvt()
: Converts a double-precision floating-point value to a string without
an embedded decimal point.
fcvt():
Same as ecvt(), but forces the precision to a specified
number of digits.
gcvt():
Converts a double-precision floating-point value to a string with
an embedded decimal point.
strtod():
Converts a string to a double-precision floating-point value and reports
any “leftover” numbers that could not be converted.
strtol():
Converts a string to a long integer and reports any “leftover” numbers
that could not be converted.
strtoul():
Converts a string to an unsigned long integer and reports any “leftover”
numbers that could not be converted.
Question
36. Differentiate Between A String Copy (strcpy) And A Memory Copy (memcpy)?
When Should Each Be Used?
Answer
:
The strcpy() function is
designed to work exclusively with strings. It copies each byte of the source
string to the destination string and stops when the terminating null character
() has been moved. On the other hand, the memcpy () function is designed to
work with any type of data. Because not all data ends with a null character,
you must provide the memcpy () function with the number of bytes you want to
copy from the source to the destination.
Question
37. How Can You Check To See Whether A Symbol Is Defined?
Answer
:
You can use the #ifdef
and #ifndef preprocessor directives to check whether a symbol has been defined
(#ifdef) or whether it has not been defined (#ifndef).
Question
38. How Do You Override A Defined Macro?
Answer
:
You can use the #undef
preprocessor directive to undefine (override) a previously defined macro.
Question
39. What Is #line Used For?
Answer
:
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.
Question
40. What Is A Pragma?
Answer
:
The #pragma preprocessor
directive allows each compiler to implement compiler-specific features that can
be turned on and off with the #pragma statement. For instance, your compiler
might support a feature called loop optimization. This feature can be invoked
as a command-line option or as a #pragma directive. To implement this option
using the #pragma directive, you would put the following line into your code:
#pragma loop_opt(on).
Question
41. What Are The Standard Predefined Macros?
Answer
:
The
ANSI C standard defines six predefined macros for use in the C language:
Macro Name Purpose
_
_LINE_ _ Inserts the current source code line number in your code.
_
_FILE_ _ Inserts the current source code filename in your code.
_
_DATE_ _ Inserts the current date of compilation in your code.
_
_TIME_ _ Inserts the current time of compilation in your code.
_
_cplusplus Is defined if you are compiling a C++ program.
Question
42. How Many Levels Deep Can Include Files Be Nested?
Answer
:
Even though there is no
limit to the number of levels of nested include files you can have, your
compiler might run out of stack space while trying to include an inordinately
high number of files. This number varies according to your hardware
configuration and possibly your compiler.
Question
43. Can Include Files Be Nested?
Answer
:
Yes. Include files can
be nested any number of times. As long as you use precautionary measures , you
can avoid including the same file twice. In the past, nesting header files was
seen as bad programming practice, because it complicates the dependency
tracking function of the MAKE program and thus slows down compilation. Many of
today’s popular compilers make up for this difficulty by implementing a concept
called precompiled headers, in which all headers and associated dependencies
are stored in a precompiled state.
Many programmers like to
create a custom header file that has #include statements for every header
needed for each module. This is perfectly acceptable and can help avoid
potential problems relating to #include files, such as accidentally omitting an
#include file in a module.
Question
44. Define Which Header File To Include At Compile Time?
Answer
:
Yes. This can be done by
using the #if, #else, and #endif preprocessor directives. For example, certain
compilers use different names for header files. One such case is between
Borland C++, which uses the header file alloc.h, and Microsoft C++, which uses
the header file malloc.h. Both of these headers serve the same purpose, and
each contains roughly the same definitions. If, however, you are writing a
program that is to support Borland C++ and Microsoft C++, you must define which
header to include at compile time. The following example shows how this can be
done:
#ifdef _ _BORLANDC_ _
#include
#else #include #endif.
Question
45. Differentiate Between #include And #include "file"?
Answer
:
When writing your C
program, you can include files in two ways. The first way is to surround the
file you want to include with the angled brackets < and >. This method of
inclusion tells the preprocessor to look for the file in the predefined default
location. This predefined default location is often an INCLUDE environment
variable that denotes the path to your include files. For instance, given the
INCLUDE variable
INCLUDE=C:\COMPILER\INCLUDE;S:\SOURCE\HEADERS;
using the
#include version of file inclusion, the compiler first checks the
C:\COMPILER\INCLUDE directory for the specified file. If the file is not found
there, the compiler then checks the S:\SOURCE\HEADERS directory. If the file is
still not found, the preprocessor checks the current directory.
The second way to
include files is to surround the file you want to include with double quotation
marks. This method of inclusion tells the preprocessor to look for the file in
the current directory first, then look for it in the predefined locations you have
set up. Using the #include “file” version of file inclusion and applying it to
the preceding example, the preprocessor first checks the current directory for
the specified file. If the file is not found in the current directory, the
C:COMPILERINCLUDE directory is searched. If the file is still not found, the
preprocessor checks the S:SOURCEHEADERS directory.
The #include method
of file inclusion is often used to include standard headers such as stdio.h or
stdlib.h. This is because these headers are rarely (if ever) modified, and they
should always be read from your compiler’s standard include file directory.
The #include “file”
method of file inclusion is often used to include nonstandard header files that
you have created for use in your program. This is because these headers are
often modified in the current directory, and you will want the preprocessor to
use your newly modified version of the header rather than the older, unmodified
version.
Question
46. Which Is Better To Use A Macro Or A Function?
Answer
:
The answer depends on
the situation you are writing code for. Macros have the distinct advantage of
being more efficient (and faster) than functions, because their corresponding
code is inserted directly into your source code at the point where the macro is
called. There is no overhead involved in using a macro like there is in placing
a call to a function. However, macros are generally small and cannot handle
large, complex coding constructs. A function is more suited for this type of
situation. Additionally, macros are expanded inline, which means that the code
is replicated for each occurrence of a macro. Your code therefore could be
somewhat larger when you use macros than if you were to use functions. Thus,
the choice between using a macro and using a function is one of deciding
between the tradeoff of faster program speed versus smaller program size.
Generally, you should use macros to replace small, repeatable code sections,
and you should use functions for larger coding tasks that might require several
lines of code.
Question
47. How Are Portions Of A Program Disabled In Demo Versions?
Answer
:
If you are distributing
a demo version of your program, the preprocessor can be used to enable or
disable portions of your program. The following portion of code shows how this
task is accomplished, using the preprocessor directives #if and #endif:
int save document(char* doc_name)
{
#if DEMO_VERSION
printf(“Sorry! You can’t save documents using
the DEMO
version of this program!n”);
return(0);
#endif
....
Question
48. What Is The Benefit Of Using An Enum Rather Than A #define Constant?
Answer
:
The use of an
enumeration constant (enum) has many advantages over using the traditional
symbolic constant style of #define. These advantages include a lower maintenance
requirement, improved program readability, and better debugging capability.
The
first advantage is that enumerated constants are generated automatically by the
compiler. Conversely, symbolic constants must be manually assigned values by
the programmer. For instance, if you had an enumerated constant type for error
codes that could occur in your program, your enum definition could look
something like this:
enum Error_Code
{
OUT_OF_MEMORY,
INSUFFICIENT_DISK_SPACE,
LOGIC_ERROR,
FILE_NOT_FOUND
};
In
the preceding example, OUT_OF_MEMORY is automatically assigned the value of 0
(zero) by the compiler because it appears first in the definition. The compiler
then continues to automatically assign numbers to the enumerated constants,
making INSUFFICIENT_DISK_SPACE equal to 1, LOGIC_ERROR equal to 2, and
FILE_NOT_FOUND equal to 3, so on. If you were to approach the same example by
using symbolic constants, your code would look something like this:
#define OUT_OF_MEMORY 0
#define INSUFFICIENT_DISK_SPACE 1
#define LOGIC_ERROR 2
#define FILE_NOT_FOUND 3
values
by the programmer. Each of the two methods arrives at the same result: four
constants assigned numeric values to represent error codes. Consider the
maintenance required, however, if you were to add two constants to represent
the error codes DRIVE_NOT_READY and CORRUPT_FILE. Using the enumeration
constant method, you simply would put these two constants anywhere in the enum
definition. The compiler would generate two unique values for these constants.
Using the symbolic constant method, you would have to manually assign two new
numbers to these constants. Additionally, you would want to ensure that the
numbers you assign to these constants are unique.
Another
advantage of using the enumeration constant method is that your programs are
more readable and thus can be understood better by others who might have to
update your program later.
A
third advantage to using enumeration constants is that some symbolic debuggers
can print the value of an enumeration constant. Conversely, most symbolic
debuggers cannot print the value of a symbolic constant. This can be an
enormous help in debugging your program, because if your program is stopped at
a line that uses an enum, you can simply inspect that constant and instantly
know its value. On the other hand, because most debuggers cannot print #define
values, you would most likely have to search for that value by manually looking
it up in a header file.
Question
49. Can A File Other Than A .h File Be Included With #include?
Answer
:
The preprocessor will
include whatever file you specify in your #include statement. Therefore, if you
have the line
#include <macros.inc>
in your program, the
file macros.inc will be included in your precompiled program. It is, however,
unusual programming practice to put any file that does not have a .h or .hpp
extension in an
#include statement.
You should always put a
.h extension on any of your C files you are going to include. This method makes
it easier for you and others to identify which files are being used for
preprocessing purposes. For instance, someone modifying or debugging your
program might not know to look at the macros.inc file for macro definitions.
That person might try in vain by searching all files with .h extensions and
come up empty. If your file had been named macros.h, the search would have
included the macros.h file, and the searcher would have been able to see what macros
you defined in it.
Question
50. Give The Benefit Of Using #define To Declare A Constant?
Answer
:
Using the #define method
of declaring a constant enables you to declare a constant in one place and use
it throughout your program. This helps make your programs more maintainable,
because you need to maintain only the #define statement and not several
instances of individual constants throughout your program. For instance, if
your program used the value of pi (approximately 3.14159) several times, you might
want to declare a constant for pi as follows:
#define PI 3.14159
Using the #define method
of declaring a constant is probably the most familiar way of declaring
constants to traditional C programmers. Besides being the most common method of
declaring constants, it also takes up the least memory. Constants defined in
this manner are simply placed directly into your source code, with no variable
space allocated in memory. Unfortunately, this is one reason why most debuggers
cannot inspect constants created using the #define method.
Question
51. How To Avoid Including A Header More Than Once?
Answer
:
One easy technique to
avoid multiple inclusions of the same header is to use the #ifndef and #define
preprocessor directives. When you create a header for your program, you can
#define a symbolic name that is unique to that header. You can use the
conditional preprocessor directive named #ifndef to check whether that symbolic
name has already been assigned. If it is assigned, you should not include the
header, because it has already been preprocessed. If it is not defined, you
should define it to avoid any further inclusions of the header. The following
header illustrates this technique:
#ifndef _FILENAME_H
#define _FILENAME_H
#define VER_NUM “1.00.00”
#define REL_DATE “08/01/94”
#if _ _WINDOWS_ _
#define OS_VER “WINDOWS”
#else
#define OS_VER “DOS”
#endif
#endif
When the preprocessor
encounters this header, it first checks to see whether _FILENAME_H has been
defined. If it hasn’t been defined, the header has not been included yet, and
the _FILENAME_H symbolic name is defined. Then, the rest of the header is
parsed until the last #endif is encountered, signaling the end of the
conditional #ifndef _FILENAME_H statement. Substitute the actual name of the header
file for “FILENAME” in the preceding example to make it applicable for your
programs.
Question
52. Differentiate Between Arrays And Pointers?
Answer
:
Pointers are used to
manipulate data using the address. Pointers use * operator to access the data
pointed to by them Arrays use subscripted variables to access and manipulate
data. Array variables can be equivalently written using pointer expression.
Question
53. Mention The Purpose Of Realloc ( )?
Answer
:
The function realloc
(ptr,n) uses two arguments. The first argument ptr is a pointer to a block of
memory for which the size is to be altered. The second argument n specifies the
new size. The size may be increased or decreased. If n is greater than the old
size and if sufficient space is not available subsequent to the old region, the
function realloc ( ) may create a new region and all the old data are moved to
the new region.
Question
54. Describe Static Memory Allocation And Dynamic Memory Allocation?
Answer
:
Static memory
allocation: The compiler allocates the required memory space for a declared
variable. By using the address of operator, the reserved address is obtained
and this address may be assigned to a pointer variable. Since most of the
declared variable has static memory, this way of assigning pointer value to a
pointer variable is known as static memory allocation. Memory is assigned
during compilation time. Dynamic memory allocation: It uses functions such as
malloc ( ) or calloc ( ) to get memory dynamically. If these functions are used
to get memory dynamically and the values returned by these functions are
assigned to pointer variables, such assignments are known as dynamic memory
allocation. Memory is assigned during run time.
Question
55. How Are Pointer Variables Initialized?
Answer
:
Pointer variable are
initialized by one of the following two ways
Static
memory allocation
Dynamic
memory allocation
Question
56. What Is A Pointer Variable?
Answer
:A pointer variable is a
variable that may contain the address of another variable or any valid address
in the memory.
Question
57. Differentiate Between Text And Binary Modes?
Answer
:
Streams can be
classified into two types: text streams and binary streams. 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. Typically, a text stream
would be used for reading and writing standard text files, printing output to
the screen or printer, or receiving input from the keyboard.
A binary text stream
would typically be used for reading and writing binary files such as graphics
or word processing documents, reading mouse input, or reading and writing to
the modem.
Question
58. How To Restore A Redirected Standard Stream?
Answer
:
The preceding example
showed how you can redirect a standard stream from within your program. But
what if later in your program you wanted to restore the standard stream to its
original state? 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.
Question
59. How To Search For Data In A Linked List?
Answer
:
Unfortunately, the only
way to search a linked list is with a linear search, because the only way a
linked list’s members can be accessed is sequentially. Sometimes it is quicker
to take the data from a linked list and store it in a different data structure
so that searches can be more efficient.
Question
60. How To Sort A Linked List?
Answer
:Both the merge sort and
the radix sort are good sorting algorithms to use for linked lists.
Question
61. What Do You Mean By Hashing?
Answer
:
To hash means to grind
up, and that’s essentially what hashing is all about. The heart of a hashing
algorithm is a hash function that takes your nice, neat data and grinds it into
some random-looking integer.
The idea behind hashing
is that some data either has no inherent ordering (such as images) or is
expensive to compare (such as images). If the data has no inherent ordering,
you can’t perform comparison searches.
If the data is expensive
to compare, the number of comparisons used even by a binary search might be too
many. So instead of looking at the data themselves, you’ll condense (hash) the
data to an integer (its hash value) and keep all the data with the same hash
value in the same place. This task is carried out by using the hash value as an
index into an array. To search for an item, you simply hash it and look at all
the data whose hash values match that of the data you’re looking for. This
technique greatly lessens the number of items you have to look at. If the
parameters are set up with care and enough storage is available for the hash
table, the number of comparisons needed to find an item can be made arbitrarily
close to one.
One aspect that affects
the efficiency of a hashing implementation is the hash function itself. It
should ideally distribute data randomly throughout the entire hash table, to
reduce the likelihood of collisions. Collisions occur when two different keys
have the same hash value. There are two ways to resolve this problem. In “open
addressing,” the collision is resolved by the choosing of another position in
the hash table for the element inserted later. When the hash table is searched,
if the entry is not found at its hashed position in the table, the search
continues checking until either the element is found or an empty position in
the table is found.
The second method of
resolving a hash collision is called “chaining.” In this method, a “bucket” or
linked list holds all the elements whose keys hash to the same value. When the
hash table is searched, the list must be searched linearly.
Question
62. Which Is The Quickest Searching Method To Use?
Answer
:
A binary search, such as
bsearch() performs, is much faster than a linear search. A hashing algorithm
can provide even faster searching. One particularly interesting and fast method
for searching is to keep the data in a “digital trie.” A digital trie offers
the prospect of being able to search for an item in essentially a constant
amount of time, independent of how many items are in the data set.
A digital trie combines
aspects of binary searching, radix searching, and hashing. The term “digital
trie” refers to the data structure used to hold the items to be searched. It is
a multilevel data structure that branches N ways at each level.
Question
63. What Is The Easiest Sorting Method To Use?
Answer
:
The answer is the
standard library function qsort(). It’s the easiest sort by far for several
reasons:
It
is already written.
It
is already debugged.
It
has been optimized as much as possible (usually).
Void qsort(void *buf, size_t num, size_t size,
int (*comp)
(const void *ele1, const void *ele2));
Question
64. Which Is The Quickest Sorting Method To Use?
Answer
:
The answer depends on
what you mean by quickest. For most sorting problems, it just doesn’t matter
how quick the sort is because it is done infrequently or other operations take
significantly more time anyway. Even in cases in which sorting speed is of the
essence, there is no one answer. It depends on not only the size and nature of
the data, but also the likely order. No algorithm is best in all cases.
There are three sorting
methods in this author’s “toolbox” that are all very fast and that are useful
in different situations. Those methods are quick sort, merge sort, and radix
sort.
The Quick Sort :The quick sort algorithm is of the “divide and conquer” type. That
means it works by reducing a sorting problem into several easier sorting
problems and solving each of them. A “dividing” value is chosen from the input
data, and the data is partitioned into three sets: elements that belong before
the dividing value, the value itself, and elements that come after the dividing
value. The partitioning is performed by exchanging elements that are in the
first set but belong in the third with elements that are in the third set but
belong in the first Elements that are equal to the dividing element can be put
in any of the three sets—the algorithm will still work properly.
The Merge Sort: The merge sort is a “divide and conquer” sort as well. It works by
considering the data to be sorted as a sequence of already-sorted lists (in the
worst case, each list is one element long). Adjacent sorted lists are merged
into larger sorted lists until there is a single sorted list containing all the
elements. The merge sort is good at sorting lists and other data structures
that are not in arrays, and it can be used to sort things that don’t fit into
memory. It also can be implemented as a stable sort.
The Radix Sort : The radix sort takes a list of integers and puts each
element on a smaller list, depending on the value of its least significant
byte. Then the small lists are concatenated, and the process is repeated for
each more significant byte until the list is sorted. The radix sort is simpler
to implement on fixed-length data such as ints.
Question
65. What Is The Benefit Of Using Const For Declaring Constants?
Answer
:
The benefit of using the
const keyword is that the compiler might be able to make optimizations based on
the knowledge that the value of the variable will not change. In addition, the
compiler will try to ensure that the values won’t be changed inadvertently.
Of course, the same
benefits apply to #defined constants. The reason to use const rather than
#define to define a constant is that a const variable can be of any type (such
as a struct, which can’t be represented by a #defined constant). Also, because
a const variable is a real variable, it has an address that can be used, if
needed, and it resides in only one place in memory.
Question
66. Is It Acceptable To Declare/define A Variable In A C Header?
Answer
:
A global variable that
must be accessed from more than one file can and should be declared in a header
file. In addition, such a variable must be defined in one source file.
Variables should not be
defined in header files, because the header file can be included in multiple
source files, which would cause multiple definitions of the variable. The ANSI
C standard will allow multiple external definitions, provided that there is
only one initialization. But because there’s really no advantage to using this
feature, it’s probably best to avoid it and maintain a higher level of
portability.
“Global” variables that
do not have to be accessed from more than one file should be declared static
and should not appear in a header file.
Question
67. When Should A Type Cast Be Used?
Answer
:
There are two situations
in which to use a type cast. The first use is to change the type of an operand
to an arithmetic operation so that the operation will be performed properly.
The second case is to
cast pointer types to and from void * in order to interface with functions that
expect or return void pointers. For example, the following line type casts the
return value of the call to malloc() to be a pointer to a foo structure.
struct foo *p = (struct foo *)
malloc(sizeof(struct foo));
Question
68. How To Determine The Maximum Value That A Numeric Variable Can Hold?
Answer
:
For integral types, on a
machine that uses two’s complement arithmetic (which is just about any machine
you’re likely to use), a signed type can hold numbers from –2(number of bits –
1) to +2(number of bits – 1) – 1. An unsigned type can hold values from 0 to
+2(number of bits) – 1. For instance, a 16-bit signed integer can hold numbers
from –2^15 (–32768) to +2^15 – 1 (32767).
Question
69. Can A Variable Be Both Const And Volatile?
Answer
:
Yes. The const modifier
means that this code cannot change the value of the variable, but that does not
mean that the value cannot be changed by means outside this code. For instance,
in the example in FAQ 8, the timer structure was accessed through a volatile
const pointer. The function itself did not change the value of the timer, so it
was declared const. However, the value was changed by hardware on the computer,
so it was declared volatile. If a variable is both const and volatile, the two
modifiers can appear in either order.
Question
70. When Does The Register Modifier Be Used? Does It Really Help?
Answer
:
The register modifier
hints to the compiler that the variable will be heavily used and should be kept
in the CPU’s registers, if possible, so that it can be accessed faster. There
are several restrictions on the use of the register modifier.
First, the variable must
be of a type that can be held in the CPU’s register. This usually means a
single value of a size less than or equal to the size of an integer. Some
machines have registers that can hold floating-point numbers as well. Second,
because the variable might not be stored in memory, its address cannot be taken
with the unary & operator. An attempt to do so is flagged as an error by
the compiler. Some additional rules affect how useful the register modifier is.
Because the number of registers is limited, and because some registers can hold
only certain types of data (such as pointers or floating-point numbers), the
number and types of register modifiers that will actually have any effect are
dependent on what machine the program will run on. Any additional register
modifiers are silently ignored by the compiler.
Also, in some cases, it
might actually be slower to keep a variable in a register because that register
then becomes unavailable for other purposes or because the variable isn’t used
enough to justify the overhead of loading and storing it.
So when should the register modifier be used? The answer is never, with most modern compilers. Early C compilers did not keep any variables in registers unless directed to do so, and the register modifier was a valuable addition to the language. C compiler design has advanced to the point, however, where the compiler will usually make better decisions than the programmer about which variables should be stored in registers. In fact, many compilers actually ignore the register modifier, which is perfectly legal, because it is only a hint and not a directive.
Q1- What is C Programming Language?
C programming language is a
computer programming language that was developed to do system programming for
the operating system UNIX and is an imperative programming language.
C was developed in 1972 by Dennis Ritchie at bell Telephone Laboratories.
It is an outgrowth of an
earlier language called B, which was also developed at Bell Laboratories.
C was largely confined to use
within Bell Laboratories until 1978, when Brian Kernighan and Ritchie Published a definitive
description of the language.
Q2- Basic structure of C
program
Structure of C program is
defined by set of rules called protocol, to be followed by programmer while
writing C program, every c programs are having these sections which are
mentioned below:
Documentation section - This is
the first part of C program.
Link - Header files that are
required to execute a C program.
Definition - In definition
section, variables are defined and values are set to these variables
Global Declaration - When a
variable is to be used throughout the program.
Function prototype declaration
Main function - Function
prototype gives many information about a function like return type, parameter
names used inside the function.
User defined function - User
can define their own functions which perform particular task as per the user
requirement.
Q3- What is a pointer in C? How
to represent pointer?
A pointer (*p) is a variable
that refers to the address of a value. It makes the code optimized & the
performance fast. Whenever a variable (i) is declared inside a program, then
the system allocates some memory to a variable. The memory contains some
address number. The variables that hold this address number is known as the
pointer variable.
Example Explained -
Example: data_type *p;
int main()
{
int *p;
int i=5;
p=&i;
printf("Address value of 'i'
variable is %u", p);
return 0;
}
The above syntax tells that p
is a pointer variable that holds the address number of a given data type value.
Q4- What is the usage of the
pointer in C?
The use of pointer in C
program, There are a small group of steps that you need to follow:
Accessing array elements
- Pointers are used to make one's way across
through an array of integers and strings. The string is an array of characters
which is terminated by a null character '\0'.
Dynamic memory allocation
- Pointers are used in allocation and
deallocation of memory during the execution of a program.
Call by Reference - Pointers are used to pass a reference of a variable to other
function.
Data Structures like a tree,
graph, linked list - The pointers are used to
construct different data structures like tree, graph, linked list etc.
Q5- When should we use pointers
in a C program?
There are some points
mentioned; When should we use pointers in a C program:
The first use of pointer to get
address of a variable
Pointers allow different
functions to share and modify their local variables.
To pass large structures so
that complete copy of the structure can be avoided.
To implement “linked” data
structures like linked lists and binary trees.
Q6- What is NULL pointer?
NULL Pointer is used to represent that the pointer doesn’t point to a
valid location. Basically, we should initialize pointers as NULL if we don’t
know their value at the time of declaration. Also, we should make a pointer
NULL when memory pointed by it is deallocated in the middle of a program.
Q7- What is a pointer on
pointer?
It’s a pointer (*p) variable
which can hold the address of another pointer (**q) variable. It de-refers
twice to point to the data held by the designated pointer variable.
Example Explained -
Example: int i=5, *p=&i,
**q=&p;
int main()
{
int i=5;
int *p, **q;
p = &i;
q = &p;
printf("value of 'i' is :
%d", i);
Printf("\n");
printf("value of '*p' is :
%d", *p);
Printf("\n");
printf("value of '**q' is :
%d", **q);
return 0;
}
Therefore " i " can
be accessed by **q.
Q8- What is embedded C
Programming?
Historically, embedded C programming requires
nonstandard extensions to the C language in order to support exotic features
such as fixed-point arithmetic, multiple distinct memory banks, and basic I/O
operations.
In 2008, the C Standards
Committee published a technical report extending the C language to address
these issues by providing a common standard for all implementations to adhere
to. It includes a number of features not available in normal C, such as
fixed-point arithmetic, named address spaces, and basic I/O hardware
addressing.
Q9- What is Integrated
Development Environment?
Integrated Development
Environment is also called IDEs, it use to compile the program.There are
several such IDEs available in the market targeted towards different operating
system. For example, Turbo C and Turbo C++ are popular compailers that work under MS-DOS; Visual
Studio 2008 and Visual Studio 2008 Express edition are the compilers that work
under windows, where is gcc compiler
work under Linux. Visual Asudio 2008 Express
edition and gcc compilers are available free of cost.
Q10- ANIS C and ISO C
In 1983, the American National Standards Institute (ANSI) formed a committee, X3J11, to establish a standard
specification of C. X3J11 based the C standard on the Unix implementation;
however, the non-portable portion of the Unix C library was handed off to the
IEEE working group 1003 to become the basis for the 1988 POSIX standard. In
1989, the C standard was ratified as ANSI X3.159-1989 "Programming
Language C". This version of the language is often referred to as ANSI C,
Standard C, or sometimes C89.
In 1990, the ANSI C standard
(with formatting changes) was adopted by the International Organization for Standardization (ISO) as ISO/IEC 9899:1990, which is sometimes called C90.
Therefore, the terms "C89" and "C90" refer to the same
programming language.
Q11- How to compile program
using Turbo C/Turbo C++ in C?
There are several steps that
you need to follow to compile and execute programs using Turbo C / Turbo C++ in C programming.
Start the compiler at C> prompt. The compiler Turbo C is
usually present in C:\TC\BIN directory.
Select New from the File menu
Type the Program
Save the program using F2 under a proper name for
example (Program1.c)
Use Ctrl+F9 to compile and
execute the program
Use Alt+F5 to view the output.
If you run this program in
Turbo C++ compiler, you may get an error - The function printf should have a prototype
Select Options menu and then select Compiler C++ options. In the
dialog box that pops up, select CPP always use
C++ compiler options.
Again select Options menu and then
select Environment Editor. Make sure that the default extension is C rather than CPP.
Q12- What is the variables and
constants in C?
A variable is a tool to reserve
space in computer's memory; and the reserved space is given a name, which we
call a variable name. Constants are stored in this reserved space. The
constants stored in the space reserved by the variable may vary from time to
time, hence the name variable. The name once given to a location, however,
remains unchanged. For example i=4; 4 is a constant which is being stored in a location which has
been give a name i. So, i is a variable just as a, x, nate or str are.
Accorrdingly memory comes in
three convenient versions - char, int, float:
A char can store values in the
range -128 to +127
Integer (int) can store values
in the rang -2147483648 to +2147483647
When we want to store numbers
like 3.1415, or 0.0005672 in memory.
A float can store values
ranging from -3.4e+38 to +3.4e+38.
The Memory occupied by each
datatype can be found out using an operator called sizeof. For example, sizeof (int) would yield 4.
Similarly, sizeof (float) would yield 4.
Q13- What is Integer and Float
Conversions in C?
It is important to understand
the rules that govern the conversion of floating point and integer values in C.
These are mentioned-
An arithmetic operation between
an integer and integer always yields an integer result.
An arithmetic operation between
a float and float always yields a float result
In an arithmetic operation
between an integer and float, the integer is first promoted to float and then the operation
is carried out. And hence it always yield a float result.
On assigning a float to an
integer using the operator, float is demoted to an integer.
On assigning an integer to a
float, it is promoted to a float.
Integer conversions |
Float conversions |
||
Operation |
Result |
Operation |
Result |
i=5/2 |
2 |
a=5/2 |
2.000000 |
i=5.0/2 |
2 |
a=5.0/2 |
2.500000 |
i=5/2.0 |
2 |
a=5/2.0 |
2.500000 |
i=2/5 |
0 |
a=2/5 |
0.000000 |
i=2.0/5 |
0 |
a=2.0/5 |
0.400000 |
i=2/5.0 |
0 |
a=2/5.0 |
0.400000 |
i=2.0/5.0 |
0 |
a=2.0/5.0 |
0.400000 |
Q14- How to use printf() and
scanf() function?
printf() is one of the most versatile statements in C programming.
In fact, it is a standerd library fuction used to display the output on the screen.
The general from of prinft()
look like:
printf("format string", list of variable);
Example - printf("name=%c age=%d
salary=%f\n", name, age, sal);
The first prinft() print the
value of the variable name, age and sal. As againest this, second would print messages against each
value displayed. In the third prinft(), the \n is used to send the cursor to
the next line.
scanf() is once again a standard library function. It is used to
receive value of variables from the keyboard. For example, the following
scanf() would let you supply the values of variables a and b.
scanf("%d %f", &a, &b)
Within the pair of double
quotes there should accur only format specifications like %c, %d, %f etc.
The variable names must always
be preceded by the 'address of operator
&'
Q15- The operators in c
language
C language supports a rich set
of built-in operators. An operator is a symbol that tells the compiler to
perform a certain mathematical or logical manipulation. Operators are used in
programs to manipulate data and variables.
Classified Operators |
Operators Types |
Arithmetic and Modulus operators |
*, /, % |
Relational Operators |
<, >, <=, >=, ==, != |
Logical (AND and OR) operators |
&& || |
Assignment operators |
=, +=, -=, *=, /=, %= |
Conditional operators |
expression 1? expression 2: expression 3 |
Bitwise operotors |
&, |, ^, <<, >> |
Special operotors |
sizeof, &, * |
Q16- What is the relational
operators? How to represent in C?
Relational Operators allow us to compare two values to see whether they are
equal to ech other, unequal, or whether one is greater than the other.
Relational Expression |
Discriptions (is true if) |
x==y |
x is equal to y |
x!=y |
x is not equal to y |
x<y |
x is less than y |
x>y |
x is greater than y |
x<=y |
x is less than or equal to y |
x>=y |
x is greater than or equal to y |
Q17- What is the Purpose Of
main() Function?
The main() Function is the
beginning function in c programming. The main function is always return
an int value to
the environment that called the program. And the program execution ends when
the closing brace of the function main() is reached. Any user defined name can
also be used as parameters for main() instead of argc and argv.
Q18- What are static functions?
The static function to specify
the “static” keyword before a function name makes it static. Unlike global
functions in C, access to static functions is restricted to the file where they
are declared. Therefore, when we want to restrict access to functions, we make
them static.
Q19- What are local static
variables? What is their use?
A local static variables
lifetime doesn’t end with a function call where it is declared. It extends for
the lifetime of complete program. All calls to the function share the same copy
of local static variables.
Static variables can be used to
count the number of times a function is called. Static variables get the default value as 0. Learn more
about variables in C programming -
Static Variable Example -
void f() {
static int i;
++i;
printf("%d", i);
}
If a global variable is static
then its visibility is limited to the same source code.
Q20- What is scope of a variable?
How are variables scoped in C?
Scope of a variable is the part
of the program where the variable may directly be accessible. In C, all
identifiers are statically scoped.
Example -
int i;
int main (void)
{
i = 2;
}
Can be accessed anywhere in a
program.
Q21- What is static memory
allocation?
In static memory allocation,
memory is allocated at compile time, and memory can't be increased while
executing the program. It is used in the array.
The lifetime of a variable in
static memory is the lifetime of a program.
The static memory is allocated
using static keyword.
The static memory is
implemented using stacks or heap.
The pointer is required to
access the variable present in the static memory.
The static memory is faster
than dynamic memory.
In static memory, more memory
space is required to store the variable.
Q22- What is dynamic memory
allocation?
In dynamic memory allocation,
memory is allocated at runtime and memory can be increased while executing the
program. It is used in the linked list.
The malloc() or calloc()
function is required to allocate the memory at the runtime.
An allocation or deallocation
of memory is done at the execution time of a program.
No dynamic pointers are
required to access the memory.
The dynamic memory is implemented
using data segments.
Less memory space is required
to store the variable.
Q23- What functions are used
for dynamic memory allocation in C?
Basically, Fore functions are
used for dynamic memory allocation in C language:
malloc()
The malloc() function is used
to allocate the memory during the execution of the program.
It does not initialize the
memory but carries the garbage value.
It returns a null pointer if it
could not be able to allocate the requested space.
calloc()
The calloc() is same as
malloc() function, but the difference only is that the fills allocated memory
with 0’s value.
realloc()
The realloc() function is used
to reallocate the memory to the new size.
If sufficient space is not
available in the memory, then the new block is allocated to accommodate the
existing data.
free()
The free() function releases
the memory allocated by either calloc() or malloc() function.
Q24- Explain modular
programming
When we are dividing the
program in to sub programs (modules/function) to achieve the given task is
modular approach. More generic functions definition gives the ability to re-use
the functions, such as built-in library functions.
Q25- What is the structure?
The structure is a user-defined
data type that allows storing multiple types of data in a single unit. It
occupies the sum of the memory of all members.
The structure members can be
accessed only through structure variables.
Structure variables accessing
the same structure but the memory allocated for each variable will be
different.
Example Explained -
struct student
{
char name[10];
int age;
}s1;
int main()
{
printf("Enter the name");
scanf("%s",s1.name);
printf("\n");
printf("Enter the age");
scanf("%d",&s1.age);
printf("\n");
printf("Name and age of a student:
%s,%d",s1.name,s1.age);
return 0;
}
Q26- What is loop in C
Language?
A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages. For example - Suppose we want to print "number" 10 times.
Q27- How many types of loops
used in C?
C programming language provides
the following types of loops to handle looping requirements.
Loop_Type_C |
Loop description |
while loop |
Repeats a statement or group of statements
while a given condition is true. It tests the condition before executing the
loop body. |
for loop |
Execute a sequence of statements multiple
times and abbreviates the code that manages the loop variable. |
do..while loop |
Like a while statement, except that it
tests the condition at the end of the loop body |
nested loops |
You can use one or more loop inside any
another while, for or do..while loop. |
Q28- What is an infinite loop?
A loop running continuously for
an indefinite number of times is called the infinite loop.
Example -
#include<stdio.h>
int main ()
{
for(; ;)
{
printf("This loop will run
forever\n");
}
return 0;
}
Infinite For Loop.
When the conditional expression
is absent, it is assumed to be true. You may have an initialization and
increment expression, but C programmers more commonly use the for(;;) construct
to signify an infinite loop.
Q29- What is a nested loop?
A loop running within another
loop is referred as a nested loop. The first loop is called Outer loop and
inside the loop is called Inner loop. Inner loop executes the number of times
define an outer loop.
Q30- What is an Arrays in C
programming? How to use array?
Arrays a kind of data structure
that can store a fixed-size sequential collection of elements of the same type.
An array is used to store a collection of data, but it is often more useful to
think of an array as a collection of variables of the same type.
Declaring Arrays -
type arrayName [arraySize];
The arraySize must be an
integer constant greater than zero and type can be any valid C data type.
All arrays consist of
contiguous memory locations. The lowest address corresponds to the first
element and the highest address to the last element.
Q31- Why do we need arrays?
We can use normal variables (v1, v2, v3,..) when we
have small number of objects, but if we want to store large number of
instances, it becomes difficult to manage them with normal variables. The idea
of array is to represent many instances in one variable.
Q32- Can the sizeof operator is 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. And one more thing remember, passing an array to a
function is exactly the same as passing a pointer to the first element. It
means that passing pointers and arrays to C functions is very efficient.
Q33- Explain about Array
Initializing
The number of values between
braces { } cannot be larger than the number of elements that we declare for the
array between square brackets [ ]. If you omit the size of the array, an array
just big enough to hold the initialization is created.
Initializing Arrays -
double salary [5] = {100.0,
1000.0, 300.50, 20.65, 400.0};
double salary [] = {100.0,
1000.0, 300.50, 20.65, 400.0};
All arrays have 0 as the index
of their first element which is also called the base index and the last index
of an array will be total size of the array minus 1.
Q34- Mention The
Characteristics Of Arrays In C
An array holds elements that
have the same data type.
Array elements are stored in
subsequent memory locations.
Two-dimensional array elements
are stored row by row in subsequent memory locations.
Array name represents the
address of the starting element.
Array size should be mentioned
in the declaration. Array size must be a constant expression and not a
variable.
Q35- What are the key features
in C programming language?
Portability – Platform independent language.
Modularity – Possibility to break down large programs into small
modules.
Flexibility – The possibility to a programmer to control the language.
Speed – C comes with support for system programming and hence it
is compiling and executes with high speed when comparing with other high-level
languages.
Extensibility – Possibility to add new features by the programmer.
Q36- What is the difference
between structs and unions?
A struct is a complex data type
that allows multiple variables to be stored in a group at a named block of
memory. Each member variable of a struct can store different data, and they all
can be used at once.
A union, on the other hand, stores the
contents of any member variable at the exact same memory location. This allows
the storage of different types of data at the same memory location. The result
is that assigning a value to one member will change the value of all the other
members. Unlike struct, only one member of the union type is likely to be
useful at any given time.
Q37- What is the difference
between C and C++?
C and C++ programming languages
are belonging to middle level languages, both are differed in below:
C Language |
C++ Language |
C is structure/procedure oriented programming language |
C++ is object oriented programming language. |
C language program design is top down approach |
C++ is using bottom up approach. |
Polymorphism, virtual function, inheritance, Operator
overloading, namespace concepts are not available in C programming language. |
C++ language supports all these concepts and features. |
C language gives importance to functions rather than
data. |
C++ gives importance to data rather than functions. |
Data and function mapping is difficult in C. |
Data and function mapping is simple in C++ that can be
done using objects. |
C language does not support user define data types. |
C++ supports user define data types. |
Exception handling is not present in C programming
language. |
Exception handling is present in C++ language. |
C language allows data to freely flow around the
functions. |
Data and functions are bound together in C++ which does
not allow data to freely flow around the functions. |
Q38- What is embedded C?
Embedded C is the extension of
C programming language.
It is used to develop micro
controller based applications.
Embedded C includes features
not available in normal C like fixed-point arithmetic, named address spaces,
and basic I/O hardware addressing.
Cell phones, MP3 players are
some example for embedded systems in which embedded C is used to program and
control these devices.
Q39- What is the difference
between assembler, compiler and interpreter?
Assembler - It is a program that converts assembly level language (low
level) into machine level language.
Compiler - Compiler compiles entire C source code into machine code.
Interpreters - It converts source code into intermediate code and then this
intermediate code is executed line by line.
Q40- Write a C program to print
- Hello, This is my first program?
Example -
#include<stdio.h>
int main ()
{
printf("Hello, This is my first
program\n");
return 0;
}
Output - Hello, This is my
first program
// printf() displays the string
inside quotation
Q41- Differentiate Between A
Linker And Linkage?
A linker converts an object
code into an executable code by linking together the necessary build in
functions. The form and place of declaration where the variable is declared in
a program determine the linkage of variable.
Q42- What is the major
difference between FOR and WHILE loop?
The major difference between
FOR and WHILE loop are as follows:
FOR and WHILE loops are entry controlled loops it means test condition is
checked for truth while entering into the loop’s body.
The FOR loop is usually
appropriate for loops in which the initialization and increment are single
statements and logically related whereas WHILE loop keeps the loop control
statements together in one place.
FOR loop is used in more
compact case comparing WHILE loop.
Q43- What is the difference
between ++x and x++?
++X - ++X is called prefixed increment and the increment will happen
first on X variable.
X++ - X++ is called postfix increment and the increment happens after
the value of X variable used for the operations.
Q44- Is C language case
sensitive?
Yes. C language
instructions/commands/functions and everything used in C program are case
sensitive.
Q45- What Are The Advantages Of
Auto Variables?
The same auto variable name can
be used in different blocks.
There is no side effect by
changing the values in the blocks.
The memory is economically
used.
Auto variables have inherent
protection because of local scope.
Q46- What Is Storage Class And
What Are Storage Variable?
A storage class is an attribute
that changes the behavior of a variable. It controls the lifetime, scope and
linkage.
There are five types of storage
classes:
auto
static
extern
register
typedef
Q47-What Is The Stack?
The stack is where all the
function's local variables are created. The stack also contains some
information used to call and return from functions.
A “stack trace” is a
list of which functions have been called, based on this information. When you
start using a debugger, one of the first things you should learn is how to get
a stack trace.
The stack is very inflexible
about allocating memory; everything must be deallocated in exactly the reverse
order it was allocated in.
Allocating memory off the stack
is extremely efficient. One of the reasons C compilers generate such good code
is their heavy use of a simple stack.
Q48- What is Macro? Why do we
use macro?
Macro is a name which is given
to a value or to a piece of code/block in a program. Instead of using the
value, we can use macro which will replace the value in a program.
Macro Syntax -
#define <MACRO_NAME>
VALUE
Q49- What Are The Standard
Predefined Macros?
The ANSI C standard defines six
predefined macros for use in the C language:
_LINE_ Inserts the current
source code line number in your code.
_FILE_ Inserts the current
source code filename in your code.
_DATE_ Inserts the current date
of compilation in your code.
_TIME_ Inserts the current time
of compilation in your code.
_cplusplus Is defined if you
are compiling a C++ program.
Q50- What are enumerations?
What is enum in C?
Enumerations are list of
integer constants with name. Enumerators are defined with the keyword enum.
It start with 0 (zero) by
default and value is incremented by 1 for the sequential identifiers in the
list.
Q51- 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.
Q52- 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.
Q53- 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.
Q54- 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.
Q55- 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.
Q56- 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 of 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.
Q57- 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 on 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.
Q58- 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.
Q59- 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 happens due to the lack of
work experience on developer's part.
Q60- 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.
Q61- 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.
Q62-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.
Q63-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.
Q64-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.
Q65-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.
Q66-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.
Q67-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.
Q68-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.
Q69-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.
Q70-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 minus 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].
Q71-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.
Q72-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.
Q73-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.
Q74-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.
Q75-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.
Q76-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 programming. They have no effect on the functionality of
the program.
Q77-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.
Q78-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.
Q79-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 include internal
leading & trailing padding used for the alignment of structure on memory
boundaries. This may cause the error.
Q80-What does *p++ do? What
does it point to?
- *p++ increments p.
- It returns the value pointed
to by p before incrementation.
Q82-Explain "Bus
Error".
- It is a fatal error in the
execution of a machine language instruction.
- It occurs because the
processor 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.
Q83-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.
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.
Q84-What will be the output of
the following?
int main()
main();
return 0;
- Runt time error. Stack
overflow.
Q85-What are the advantages of
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.
Q86-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.
Q87-Explain the following.
a.) Queue b.) Priority Queues -
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.
Q88-Explain the following.
a. ) Binary height balanced
tree b.) Ternary tree c.) Red-black trees
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 properties:
- Root is black.
- Every leaf is black.
- Every node is either red or
black.
- For a red node, both its
children are black.
- All internal nodes have two
children .
- Every simple path from a node
to a descendant leaf contains the same number of black nodes.
Q89-What is "Bus
error"?
A ‘bus error’ is certain
undefined behavior result type. The cause for such error in 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.
Q90-Throw some light on the
following.
a.) Splay trees b.) B tree
a.) Splay trees -
- These are self adjusting
binary search trees.
- They can adjust optimally to
any sequence of tree operations.
- Everytime 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 at least 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.
Q91-Explain - a.) Threaded
binary trees b.) B+ tree
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.
Q92-Differentiate between
full, complete & perfect binary trees.
Full binary tree - Each node is
either a leaf or an 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.
Q93-Explain the use of keyword
'register' with respect to variables.
- It specifies that a 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.
Q94-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
Q95-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.
Q96-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.
Q97-Explain the properties of
union. What is the size of a union variable
- With Union same storage can
be referenced in different ways.
- 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.
Q98-What is the format
specifier for printing a pointer value?
- %p format specifier displays
the corresponding argument that is a pointer.
- %x can be used to print a
value in hexadecimal format.
Q99-Why can arithmetic
operations not be performed on void 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.
Q100-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.
Q101-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 tri-graph and allow it to be used with the
system.
b) The second stage is to
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.
Q102-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 don’t 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.
Q103-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 a 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.
Q104-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 referred as
the same object if they are preceded with the external linkage. For example
printf() is declared externally in 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++;
}
Q105-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;
}
Q106-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.
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 is given below:
#pragma pragma-string.
#include
#pragma pragma-string
int main(){
printf("C is powerful
language ");
return 0;
}
Q107-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: 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: 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: 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: 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.
Q108-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.
Q109-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.
Q110-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 expression2. 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);
Q111-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.
Q112-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
datatype. 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 result 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;
Q113-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.
Q114-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.
Q115-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.
Q116-What is a dangling
pointer?
A dangling pointer is one that
has a value (not NULL) which refers to some memory which is not valid for the
type of object you expect. For example if you set a pointer to an object then
overwrote that memory with something else unrelated or freed the memory if it
was dynamically allocated.
Q117-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.
Q118-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
Q119-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 declaration 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.
Q120-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.
Q121-What are “near” and “far”
pointers?
“Near” and “Far” pointers are
system specific and the use of it, has been decreased over the years, it has
now become obsolete. These are supported by 16-bit programming languages. To
know the machine that doesn’t require these kinds of pointers, use a
preprocessor or remove the unnecessary “near”, “far” pointer keywords.
Q122-Why can’t 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-byte
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.
Q123-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.
Q124-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.
Q125-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
Q126-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.
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.
Q127-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 available 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
Q128-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.
Q129-What are storage classes
in C?
a.) Automatic storage classes :
Variable with block scope but without static specifier.
b.) Static storage classes:
Variables with block scope and with static specifier. Global variables with or
without static specifier.
c.) Allocated storage classes:
Memory obtained from calls to malloc(), alloc() or realloc().
Q130-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
Q131-How do you initialize
pointer variables?
Pointer variables are
initialized in two ways:
- By static memory allocation
- By dynamic memory allocation
Q132-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.
Q133-What are the advantages 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 program
becomes difficult.
- It affects the generality of
the program.
Q134-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.
Q135-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.
Q136-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.
Q137-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.
Q138-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.
Q139-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
two 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.
Q140-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[]);
Q141-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.
Q142-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.
Q143-What are pointers? Why are
they used?
Pointers are variables which
store the address of other variables.
Advantages of using pointers:
- They allow to pass values to
functions using call by reference - especially useful while large sized arrays
are passed as arguments to functions.
- They allow dynamic allocation
of memory.
- They help in resizing the
data structures.
Q144-How can I change the size of the dynamically allocated
array?
You can change the size of the
array if it is defined dynamically, by using the realloc() function. realloc()
function’s syntax is written as:
dynarray = realloc(dynarray, 20
* sizeof(int));
But, realloc() function can’t
just enlarge the memory, and this memory allocation depends on the space
available in the system. If realloc() can’t find the space available, then it
returns null pointer.
Q145-How to write a multi-statement macro?
Macro are simple statements
which are written to, dynamically execute the method or function. The function
call syntax is:
MACRO(arg1, arg2);
Macro can be included with the
conditional statements using the external else clause. You can include simple
expressions in macro with no declarations or loops like:
#define FUNC(arg1, arg2)
(expr1, expr2, expr3)
Q146-What's the right way to use errno?
The errors should be checked by
return values. Errno defines among various causes of an error, such as “File
not found” or “Permission denied”. Errno detects only when a function doesn’t
have a unique or unambiguous errors. Errno can be set manually to 0 to find the
errors. Error messages can be made useful if the program name with the error
can be printed so that the error can be noticed and solved.
Q147-Why can't I perform arithmetic on a void* pointer?
There are no arithmetic
operations that can be performed on void* pointer is because the compiler
doesn’t know the size of the pointed objects. Arithmetic operations can only be
done on the pointed objects. Some compilers make it an exception to perform the
arithmetic functions on the pointer.
Q148 -How can I return multiple values from a function?
A function can return multiple
values in several ways by using the pointers. These include the examples like
hypothetical calculation of polar-to-rectangular coordinate functions. The
pointer allows you to have a function in which you can pass multiple values and
use them.
Example code:
#include
polar_to_rectangular(double a,
double b, double *xp, double *yp)
{ a=10;
b=20;
*xp = a;
*yp = b;
}
Q149-What's the total generic pointer type?
There is nothing like total
generic pointer type, only void* holds the object (i.e. data) pointers.
Converting function pointer to type void* is not a portable and it is not
appropriate to convert it also. You can use any function type like int*() or
void*(), these pointers can be treated as a generic function pointer. The best
way to have the portability, is to use void* and a generic pointer combination.
Q150- 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.