Top 100+ C Interview Questions And Answers
Question 1. Explain The Purpose Of Main( ) Function?
The feature foremost( ) invokes other capabilities inside it.It is the primary characteristic to be referred to as whilst this system begins execution.
It is the beginning feature.
It returns an int value to the surroundings that called the program.
Recursive call is authorized for main( ) additionally.
It is a person-described feature.
Program execution ends when the ultimate brace of the characteristic important( ) is reached.
It has arguments argument depend and.
Argument vector (represents strings passed).
Any person-defined name can also be used as parameters for primary( ) in preference to argc and argv.
Question 2. Write The Equivalent Expression For X%8?
DBMS Interview Questions
Question three. Why N++ Executes Faster Than N+1?
The expression n++ requires a single machine instruction consisting of INR to perform the increment operation whereas n+1 requires more commands to carry out this operation.
Question four. Can The Sizeof Operator Be Used To Tell The Size Of An Array Passed To A Function?
No. There’s no manner to inform, at runtime, how many elements are in an array parameter just by using searching at the array parameter itself. Remember, passing an array to a feature is exactly the same as passing a pointer to the first detail.
Question 5. Is Using Exit () The Same As Using Return?
No. The go out () feature is used to go out your application and return manage to the operating system. The return assertion is used to return from a characteristic and go back control to the calling feature. If you problem a return from the principle () characteristic, you are essentially returning control to the calling function, which is the working system. In this example, the go back declaration and go out () function are similar.
C++ Interview Questions
Question 6. What Is A Function And Built-in Function?
A large application is subdivided into some of smaller programs or subprograms. Each subprogram specifies one or extra moves to be completed for a big program. Such subprograms are features. The function supports only static and extern garage training. By default, feature assumes extern garage elegance. Functions have international scope. Only sign in or car storage magnificence is permitted inside the function parameters. Built-in features that predefined and furnished along side the compiler are called built-in features. They also are known as library capabilities.
Question 7. Write About Modular Programming?
If a application is large, it's far subdivided into some of smaller applications which can be known as modules or subprograms. If a complex hassle is solved the use of extra modules, this technique is called modular programming.
Java Tutorial C & Data Structures Interview Questions
Question 8. When Does The Compiler Not Implicitly Generate The Address Of The First Element Of An Array?
Whenever an array name appears in an expression consisting of,
array as an operand of the sizeof operator.
Array as an operand of & operator.
Array as a string literal initializer for a individual array.
Then the compiler does not implicitly generate the cope with of the cope with of the primary element of an array.
Question 9. Mention The Characteristics Of Arrays In C?
An array holds factors that have the identical statistics kind.
Array elements are stored in subsequent memory places.
Two-dimensional array factors are saved row by using row in subsequent memory locations.
Array call represents the address of the starting detail.
Array length need to be referred to within the assertion. Array length ought to be a constant expression and now not a variable.
Java Interview Questions
Question 10. Differentiate Between A Linker And Linkage?
A linker converts an object code into an executable code by linking collectively the vital build in functions. The shape and location of announcement where the variable is declared in a program decide the linkage of variable.
Go (programming language) Tutorial
Question eleven. What Are The Advantages Of Auto Variables?
The identical automobile variable name can be utilized in distinct blocks.
There is no side impact via changing the values inside the blocks.
The reminiscence is economically used.
Auto variables have inherent safety because of neighborhood scope.
Go (programming language) Interview Questions
Question 12. What Is Storage Class And What Are Storage Variable?
A garage magnificence is an characteristic that adjustments the behavior of a variable. It controls the lifetime, scope and linkage. There are five varieties of storage training.
DBMS Interview Questions
Question 13. Which Expression Always Return True? Which Always Return False?
expression if (a=0) always return fake.
Expression if (a=1) usually return authentic.
F Sharp (programming language) Tutorial
Question 14. Is It Possible To Execute Code Even After The Program Exits The Main () Function?
The general C library offers a feature named at exit () that can be used to carry out “cleanup” operations while your program terminates. You can set up a set of capabilities you want to carry out mechanically when your software exits with the aid of passing function guidelines to the at exit() function.
Question 15. Why Should I Prototype A Function?
A function prototype tells the compiler what kind of arguments a function is looking to receive and what type of go back value a characteristic goes to give lower back. This approach facilitates the compiler make certain that calls to a characteristic are made effectively and that no faulty type conversions are taking area.
F Sharp (programming language) Interview Questions
Question sixteen. How Do You Print An Address?
The safest manner is to apply printf () (or fprintf() or sprintf()) with the %P specification. That prints a void pointer (void*). Different compilers might print a pointer with extraordinary formats. Your compiler will select a layout that’s proper in your surroundings.
If you have a few different form of pointer (now not a void*) and also you need to be very secure, forged the pointer to a void*:
printf (“%Pn”, (void*) buffer);
R Programming language Tutorial
Question 17. Can Math Operations Be Performed On A Void Pointer?
No. Pointer addition and subtraction are based totally on advancing the pointer by means of a number of factors. By definition, when you have a void pointer, you don’t understand what it’s pointing to, so you don’t recognize the size of what it’s pointing to. If you want pointer mathematics to work on raw addresses, use man or woman pointers.
C preprocessor Interview Questions
Question 18. How Can You Determine The Size Of An Allocated Portion Of Memory?
You can’t, truly unfastened() can , but there’s no way for your application to realize the trick loose() uses. Even in case you disassemble the library and discover the trick, there’s no assure the trick gained’t alternate with the next launch of the compiler.
C++ Interview Questions
Question 19. What Is A "null Pointer Assignment" Error? What Are Bus Errors, Memory Faults, And Core Dumps?
These are all extreme mistakes, signs of a wild pointer or subscript. Null pointer project is a message you would possibly get whilst an MS-DOS program finishes executing. Some such programs can arrange for a small amount of memory to be available “wherein the NULL pointer factors to” (so to speak). If this system attempts to jot down to that region, it will overwrite the data placed there by means of the compiler. When this system is performed, code generated via the compiler examines that area. If that records has been modified, the compiler-generated code complains with null pointer task.
This message includes only enough statistics to get you worried. There’s no way to inform, simply from a null pointer undertaking message, what part of your application is liable for the mistake. Some debuggers, and some compilers, can provide you with extra assist in locating the hassle. Bus error: center dumped and Memory fault: core dumped are messages you would possibly see from a software going for walks underneath UNIX. They’re extra programmers pleasant. Both imply that a pointer or an array subscript become wildly out of bounds. You can get those messages on a read or on a write. They aren’t confined to null pointer troubles.
The center dumped part of the message is telling you approximately a record, called middle that has simply been written to your modern-day directory. This is a unload of the whole lot on the stack and in the heap at the time this system become walking. With the assist of a debugger, you may use the middle dump to find where the bad pointer turned into used. That might not inform you why the pointer turned into terrible, however it’s a step within the right course. If you don’t have write permission in the current directory, you gained’t get a center record, or the middle dumped message.
D Programming Language Tutorial
Question 20. What Is The Heap?
The heap is in which malloc(), calloc(), and realloc() get memory.
Getting memory from the heap is tons slower than getting it from the stack. On the other hand, the heap is much extra flexible than the stack. Memory can be allocated at any time and deallocated in any order. Such reminiscence isn’t deallocated routinely; you have to call loose ().
Recursive information structures are nearly continually applied with reminiscence from the heap. Strings regularly come from there too, in particular strings that might be very long at runtime. If you may hold statistics in a nearby variable (and allocate it from the stack), your code will run faster than if you positioned the information on the heap. Sometimes you may use a better set of rules if you use the heap—quicker, or more strong, or extra bendy. It’s a tradeoff.
If memory is allocated from the heap, it’s to be had until the program ends. That’s first rate if you take into account to deallocate it while you’re done. If you overlook, it’s a hassle. A “memory leak” is some allocated memory that’s now not wished however isn’t deallocated. If you've got a memory leak inside a loop, you could deplete all the memory at the heap and now not be capable of get any greater. (When that occurs, the allocation capabilities go back a null pointer.) In some environments, if a software doesn’t deallocate everything it allotted, reminiscence stays unavailable even after the program ends.
R Programming language Interview Questions
Question 21. Difference Between Null And Nul?
NULL is a macro described in for the null pointer. NUL is the call of the first individual within the ASCII character set. It corresponds to a zero price. There’s no widespread macro NUL in C, but a few human beings like to outline it.
The digit zero corresponds to a price of eighty, decimal. Don’t confuse the digit zero with the cost of ‘’ (NUL)!
NULL can be described as ((void*)zero), NUL as ‘ ’.
Question 22. What Is The Stack?
The stack is in which all of the capabilities’ nearby (automobile) variables are created. The stack additionally carries some statistics used to call and go back from capabilities.
A “stack hint” is a listing of which features were called, primarily based on this data. When you start using a debugger, one of the first stuff you need to learn is the way to get a stack hint. The stack could be very rigid approximately allocating memory; the entirety need to be deallocated in precisely the reverse order it became allocated in. For implementing function calls, that is all that’s needed. Allocating reminiscence off the stack is extremely green. One of the motives C compilers generate such top code is their heavy use of a easy stack.
There was a C feature that any programmer could use for allocating reminiscence off the stack. The reminiscence was robotically deallocated whilst the calling function back. This became a dangerous characteristic to call; it’s now not available anymore.
Lua (programming language) Tutorial
Question 23. When Should A Far Pointer Be Used?
Sometimes you could break out with the use of a small memory version in maximum of a given application. There is probably only a few matters that don’t match on your small records and code segments. When that happens, you may use specific a long way recommendations and feature declarations to get on the relaxation of memory. A a long way feature may be outside the 64KB segment maximum functions are shoehorned into for a small-code model. (Often, libraries are declared explicitly far, in order that they’ll paintings regardless of what code version the program makes use of.)
A far pointer can discuss with data outside the 64KB facts segment. Typically, such tips are used with farmalloc () and such, to control a heap cut loose in which all of the relaxation of the facts lives. If you use a small-data, massive-code version, you should explicitly make your function pointers a long way.
D Programming Language Interview Questions
Question 24. Differentiate Between Far And Near?
Some compilers for PC compatibles use two forms of recommendations. Near guidelines are 16 bits long and may address a 64KB range. Some distance suggestions are 32 bits long and may cope with a 1MB variety.
Near recommendations function within a 64KB segment. There’s one phase for feature addresses and one section for statistics. Some distance suggestions have a sixteen-bit base (the section address) and a sixteen-bit offset. The base is increased via 16, so a much pointer is efficiently 20 bits lengthy. Before you collect your code, you must tell the compiler which reminiscence version to apply. If you use a small code reminiscence version, near suggestions are used by default for feature addresses.
That means that every one the functions need to healthy in a single 64KB segment. With a huge-code version, the default is to use a ways feature addresses. You’ll get close to hints with a small records version, and far guidelines with a huge records version. These are just the defaults; you could declare variables and functions as explicitly close to or far.
Far recommendations are a bit slower. Whenever one is used, the code or records section register needs to be swapped out. Far suggestions also have abnormal semantics for mathematics and comparison. For example, the 2 a ways guidelines within the preceding instance point to the equal deal with, but they would compare as distinct! If your software fits in a small-information, small-code reminiscence version, your life may be less complicated.
C & Data Structures Interview Questions
Question 25. Is It Better To Use Malloc () Or Calloc ()?
Both the malloc() and the calloc() features are used to allocate dynamic reminiscence. Each operates barely specific from the other. Malloc() takes a size and returns a pointer to a piece of reminiscence at the least that massive:
void *malloc( size_t length );
calloc() takes some of elements, and the scale of every, and returns a pointer to a chunk of reminiscence at the least massive enough to maintain them all:
void *calloc( size_t numElements,size_t sizeOfElement );
There’s one important difference and one minor difference among the 2 functions. The primary distinction is that malloc () doesn’t initialize the allotted reminiscence. The first time malloc () gives you a specific chew of reminiscence, the reminiscence is probably full of zeros. If memory has been allocated, freed, and reallocated, it possibly has whatever junk become left in it. That method, unluckily, that a application might run in simple cases (whilst reminiscence is by no means reallocated) but wreck when used harder (and whilst reminiscence is reused). Calloc() fills the allocated reminiscence with all 0 bits. That approach that some thing there you’re going to use as a char or an int of any length, signed or unsigned, is guaranteed to be 0. Anything you’re going to apply as a pointer is about to all 0 bits. That’s typically a null pointer, but it’s not assured. Anything you’re going to apply as a go with the flow or double is set to all 0 bits; that’s a floating-point zero on a few sorts of machines, but no longer on all.
The minor difference among the 2 is that calloc () returns an array of gadgets; malloc () returns one item. Some humans 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?
This is paranoia based on long enjoy. After a pointer has been freed, you may not use the pointed-to statistics. The pointer is stated to “hold”; it doesn’t point at some thing beneficial. If you “NULL out” or “zero out” a pointer immediately after releasing it, your program can now not get in hassle by way of using that pointer. True, you might pass indirect at the null pointer alternatively, but that’s some thing your debugger is probably able to help you with right now. Also, there still is probably copies of the pointer that confer with the reminiscence that has been deallocated; that’s the nature of C. Zeroing out recommendations after liberating them won’t clear up all issues.
Lua (programming language) Interview Questions
Question 27. When Would You Use A Pointer To A Function?
Pointers to capabilities are thrilling when you pass them to other functions. A function that takes feature recommendations says, in effect, “Part of what I do can be customized. Give me a pointer to a characteristic, and I’ll name it when that a part of the task desires to be completed. That characteristic can do its part for me.” This is referred to as a “callback.” It’s used loads in graphical consumer interface libraries, in which the fashion of a display is constructed into the library but the contents of the display are a part of the software.
As a less complicated example, say you have got an array of individual suggestions (char*s), and you need to kind it by means of the value of the strings the character tips factor to. The preferred qsort() feature uses characteristic guidelines to carry out that project. Qsort() takes four arguments,
a pointer to the beginning of the array,
the number of elements inside the array,
the dimensions of each array detail, and,
a contrast characteristic, and returns an int.
Java Interview Questions
Question 28. What Does It Mean When A Pointer Is Used In An If Statement?
Any time a pointer is used as a condition, it way “Is this a non-null pointer?” A pointer can be utilized in an if, while, for, or do/whilst declaration, or in a conditional expression.
Question 29. Is Null Always Defined As 0?
NULL is defined as either 0 or (void*)0. These values are almost identical; either a literal 0 or a void pointer is converted automatically to any type of pointer, as vital, each time a pointer is needed (despite the fact that the compiler can’t always inform when a pointer is wanted).
Embedded C Interview Questions
Question 30. What Is A Null Pointer?
There are times when it’s vital to have a pointer that doesn’t point to whatever. The macro NULL, defined in , has a fee that’s guaranteed to be special from any legitimate pointer. NULL is a literal zero, probable forged to void* or char*. Some humans, notably C++ programmers, opt to use 0 in place of NULL. The null pointer is used in three approaches:
To forestall indirection in a recursive data structure
As an blunders value
As a sentinel value
Question 31. Mention The Levels Of Pointers Can You Have?
The solution relies upon on what you imply by means of “tiers of hints.” If you imply “How many levels of indirection can you have in a single announcement?” the answer is “At least 12.”
int i = zero;
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 fashionable says all compilers have to manage at the least 12 stages. Your compiler might assist more.
Question 32. What Is Indirection?
Answer :If you declare a variable, its name is a direct connection with its value. If you have got a pointer to a variable or some other item in memory, you have an indirect reference to its fee.
Question 33. How Do You Print Only Part Of A String?
/* Use printf () to print the first eleven characters of source_str. */
printf (“First 11 characters: ‘%11.11s’n”, source_str);
Go (programming language) Interview Questions
Question 34. How To Convert A String To A Number?
The general C library affords several functions for converting strings to numbers of all codecs (integers, longs, floats, and so on) and vice versa.
The following functions can be used to transform strings to numbers:
Function Name Purpose
atof(): Converts a string to a double-precision floating-factor price.
Atoi(): Converts a string to an integer.
Atol(): Converts a string to a protracted integer.
Question 35. How To Convert A Number To A String?
The preferred C library provides numerous features for converting numbers of all formats (integers, longs, floats, and so on) to strings and vice versa The following features may be used to transform integers to strings:
Function Name Purpose
iota(): Converts an integer price to a string.
Ltoa (): Converts an extended integer fee to a string.
Ultoa (): Converts an unsigned lengthy integer cost to a string.
The following features may be used to transform floating-factor values to strings:
Function Name Purpose
ecvt() : Converts a double-precision floating-factor fee to a string without an embedded decimal factor.
Fcvt(): Same as ecvt(), but forces the precision to a targeted variety of digits.
Gcvt(): Converts a double-precision floating-factor value to a string with an embedded decimal factor.
Strtod(): Converts a string to a double-precision floating-point value and reviews any “leftover” numbers that couldn't be transformed.
Strtol(): Converts a string to a long integer and reports any “leftover” numbers that could not be transformed.
Strtoul(): Converts a string to an unsigned lengthy integer and reports any “leftover” numbers that couldn't be converted.
Question 36. Differentiate Between A String Copy (strcpy) And A Memory Copy (memcpy)? When Should Each Be Used?
The strcpy() characteristic is designed to work completely with strings. It copies every byte of the source string to the vacation spot string and forestalls when the terminating null person () has been moved. On the alternative hand, the memcpy () characteristic is designed to paintings with any sort of statistics. Because no longer all information ends with a null man or woman, you need to offer the memcpy () characteristic with the range of bytes you need to duplicate from the supply to the destination.
F Sharp (programming language) Interview Questions
Question 37. How Can You Check To See Whether A Symbol Is Defined?
You can use the #ifdef and #ifndef preprocessor directives to test whether a symbol has been described (#ifdef) or whether it has no longer been described (#ifndef).
Question 38. How Do You Override A Defined Macro?
You can use the #undef preprocessor directive to undefine (override) a previously defined macro.
Question 39. What Is #line Used For?
The #line preprocessor directive is used to reset the values of the _ _LINE_ _ and _ _FILE_ _ symbols, respectively. This directive is generally utilized in fourth-era languages that generate C language supply documents.
Question forty. What Is A Pragma?
The #pragma preprocessor directive permits every compiler to put in force compiler-specific capabilities that can be turned on and off with the #pragma assertion. For example, your compiler may guide a function referred to as loop optimization. This characteristic can be invoked as a command-line option or as a #pragma directive. To enforce this selection the use of the #pragma directive, you will positioned the following line into your code:
C preprocessor Interview Questions
Question forty one. What Are The Standard Predefined Macros?
The ANSI C preferred defines six predefined macros for use within the C language:
Macro Name Purpose
_ _LINE_ _ Inserts the current source code line variety on your code.
_ _FILE_ _ Inserts the contemporary source code filename on your code.
_ _DATE_ _ Inserts the current date of compilation on your code.
_ _TIME_ _ Inserts the contemporary time of compilation on your code.
_ _cplusplus Is described if you are compiling a C++ application.
Question 42. How Many Levels Deep Can Include Files Be Nested?
Even though there may be no restriction to the range of levels of nested include files you could have, your compiler might run out of stack space even as seeking to consist of an inordinately high wide variety of documents. This number varies according to your hardware configuration and possibly your compiler.
R Programming language Interview Questions
Question forty three. Can Include Files Be Nested?
Yes. Include files may be nested any quantity of times. As long as you use precautionary measures , you may avoid along with the same report twice. In the beyond, nesting header files turned into seen as terrible programming practice, as it complicates the dependency tracking characteristic of the MAKE program and for that reason slows down compilation. Many of nowadays’s famous compilers make up for this difficulty by way of implementing a concept referred to as precompiled headers, in which all headers and related dependencies are stored in a precompiled country.
Many programmers like to create a custom header document that has #consist of statements for each header wished for every module. This is flawlessly suited and may help avoid capability problems relating to #include files, along with by chance omitting an #encompass report in a module.
Question forty four. Define Which Header File To Include At Compile Time?
Yes. This may be completed by using using the #if, #else, and #endif preprocessor directives. For example, positive compilers use different names for header documents. One such case is between Borland C++, which uses the header document alloc.H, and Microsoft C++, which makes use of the header file malloc.H. Both of those headers serve the equal motive, and each carries roughly the equal definitions. If, but, you are writing a application this is to assist Borland C++ and Microsoft C++, you ought to define which header to encompass at collect time. The following example shows how this will be performed:
#ifdef _ _BORLANDC_ _
#include #else #include #endif.
Question forty five. Differentiate Between #consist of And #encompass "file"?
When writing your C software, you could encompass documents in two methods. The first way is to surround the file you need to encompass with the angled brackets < and >. This approach of inclusion tells the preprocessor to search for the report in the predefined default vicinity. This predefined default area is frequently an INCLUDE environment variable that denotes the route to your consist of documents. For instance, given the INCLUDE variable
the usage of the #include version of report inclusion, the compiler first tests the C:COMPILERINCLUDE directory for the required record. If the record isn't found there, the compiler then exams the S:SOURCEHEADERS listing. If the report is still not found, the preprocessor checks the modern listing.
The 2nd manner to encompass files is to surround the file you want to include with double citation marks. This technique of inclusion tells the preprocessor to search for the record inside the modern-day directory first, then search for it within the predefined locations you have got set up. Using the #encompass “document” version of report inclusion and applying it to the preceding example, the preprocessor first checks the current listing for the specified document. If the file isn't always discovered in the present day listing, the C:COMPILERINCLUDE directory is searched. If the document continues to be no longer found, the preprocessor checks the S:SOURCEHEADERS directory.
The #consist of approach of record inclusion is regularly used to include fashionable headers such as stdio.H or stdlib.H. This is because these headers are hardly ever (if ever) changed, and that they have to continually be study from your compiler’s general include file directory.
The #include “file” technique of document inclusion is regularly used to include nonstandard header files which you have created to be used in your software. This is because these headers are often modified within the contemporary directory, and you will want the preprocessor to use your newly modified model of the header in preference to the older, unmodified version.
Question 46. Which Is Better To Use A Macro Or A Function?
The solution depends on the situation you're writing code for. Macros have the wonderful gain of being extra efficient (and quicker) than capabilities, due to the fact their corresponding code is inserted directly into your source code on the factor wherein the macro is called. There isn't any overhead involved in using a macro like there's in putting a name to a characteristic. However, macros are normally small and cannot take care of big, complex coding constructs. A function is greater suited for this sort of scenario. Additionally, macros are extended inline, which means that the code is replicated for each prevalence of a macro. Your code consequently could be quite large when you use macros than in case you had been to apply capabilities. Thus, the selection between using a macro and using a characteristic is one among deciding between the tradeoff of faster software pace versus smaller software size. Generally, you need to use macros to replace small, repeatable code sections, and you must use functions for large coding tasks that could require numerous traces of code.
Question 47. How Are Portions Of A Program Disabled In Demo Versions?
If you are distributing a demo model of your program, the preprocessor may be used to allow or disable quantities of your application. The following part of code shows how this mission is done, the use of the preprocessor directives #if and #endif:
int save record(char* doc_name)
printf(“Sorry! You can’t shop documents the use of the DEMO
version of this program!N”);
Question forty eight. What Is The Benefit Of Using An Enum Rather Than A #outline Constant?
The use of an enumeration consistent (enum) has many blessings over the use of the conventional symbolic consistent style of #outline. These advantages consist of a lower upkeep requirement, advanced application clarity, and better debugging capability.
The first benefit is that enumerated constants are generated routinely by the compiler. Conversely, symbolic constants should be manually assigned values through the programmer. For instance, in case you had an enumerated steady kind for mistakes codes that would arise on your program, your enum definition should look some thing like this:
In the previous instance, OUT_OF_MEMORY is mechanically assigned the price of zero (zero) by means of the compiler because it seems first inside the definition. The compiler then continues to routinely assign numbers to the enumerated constants, making INSUFFICIENT_DISK_SPACE same to one, LOGIC_ERROR equal to 2, and FILE_NOT_FOUND equal to 3, so on. If you were to approach the identical example through using symbolic constants, your code might appearance something like this:
#outline OUT_OF_MEMORY 0
#outline INSUFFICIENT_DISK_SPACE 1
#outline LOGIC_ERROR 2
#outline FILE_NOT_FOUND three
values by using the programmer. Each of the two methods arrives at the same result: 4 constants assigned numeric values to symbolize blunders codes. Consider the upkeep required, however, in case you have been to add two constants to symbolize the mistake codes DRIVE_NOT_READY and CORRUPT_FILE. Using the enumeration constant technique, you in reality would positioned those two constants everywhere inside the enum definition. The compiler might generate particular values for these constants. Using the symbolic constant technique, you would have to manually assign new numbers to these constants. Additionally, you would need to make certain that the numbers you assign to those constants are specific.
Another advantage of the usage of the enumeration constant technique is that your applications are greater readable and thus can be understood higher by means of others who would possibly must update your program later.
A 0.33 gain to using enumeration constants is that some symbolic debuggers can print the cost of an enumeration regular. Conversely, most symbolic debuggers cannot print the fee of a symbolic consistent. This can be an significant assist in debugging your software, due to the fact in case your application is stopped at a line that uses an enum, you could simply investigate that regular and right away know its fee. On the opposite hand, because maximum debuggers can not print #define values, you'll most possibly should search for that value by means of manually looking it up in a header report.
Question 49. Can A File Other Than A .H File Be Included With #consist of?
The preprocessor will consist of something file you specify for your #consist of statement. Therefore, when you have the road
in your program, the document macros.Inc may be covered for your precompiled program. It is, but, uncommon programming exercise to put any file that does not have a .H or .Hpp extension in an
#consist of statement.
You should constantly placed a .H extension on any of your C documents you are going to consist of. This technique makes it easier for you and others to discover which documents are getting used for preprocessing purposes. For example, someone editing or debugging your application won't recognize to take a look at the macros.Inc document for macro definitions. That man or woman might try in vain via searching all files with .H extensions and arise empty. If your report were named macros.H, the search could have covered the macros.H file, and the searcher might were able to see what macros you described in it.
Question 50. Give The Benefit Of Using #define To Declare A Constant?
Using the #define technique of affirming a steady enables you to declare a regular in a single vicinity and use it throughout your software. This allows make your applications greater maintainable, due to the fact you need to maintain best the #outline assertion and no longer several times of person constants throughout your software. For example, if your application used the fee of pi (about three.14159) several times, you would possibly need to claim a consistent for pi as follows:
#outline PI 3.14159
Using the #define method of putting forward a regular is probably the most familiar way of affirming constants to standard C programmers. Besides being the maximum commonplace approach of affirming constants, it additionally takes up the least memory. Constants defined in this manner are definitely positioned immediately into your supply code, with out a variable space allocated in reminiscence. Unfortunately, that is one reason why maximum debuggers can not look into constants created the use of the #define technique.
Question fifty one. How To Avoid Including A Header More Than Once?
One clean technique to keep away from more than one inclusions of the same header is to use the #ifndef and #define preprocessor directives. When you create a header for your software, you could #outline a symbolic call that is specific to that header. You can use the conditional preprocessor directive named #ifndef to check whether that symbolic call has already been assigned. If it's far assigned, you must now not consist of the header, as it has already been preprocessed. If it is not described, you ought to define it to avoid any in addition inclusions of the header. The following header illustrates this approach:
#define VER_NUM “1.00.00”
#outline REL_DATE “08/01/ninety four”
#if _ _WINDOWS_ _
#outline OS_VER “WINDOWS”
#outline OS_VER “DOS”
When the preprocessor encounters this header, it first tests to look whether or not _FILENAME_H has been described. If it hasn’t been described, the header has no longer been covered yet, and the _FILENAME_H symbolic call is defined. Then, the relaxation of the header is parsed until the ultimate #endif is encountered, signaling the give up of the conditional #ifndef _FILENAME_H assertion. Substitute the actual call of the header document for “FILENAME” in the previous instance to make it applicable for your programs.
Question 52. Differentiate Between Arrays And Pointers?
Pointers are used to govern information the usage of the cope with. Pointers use * operator to access the information pointed to by way of them Arrays use subscripted variables to get right of entry to and control statistics. Array variables can be equivalently written using pointer expression.
Question 53. Mention The Purpose Of Realloc ( )?
The feature realloc (ptr,n) uses arguments. The first argument ptr is a pointer to a block of memory for which the dimensions is to be altered. The 2d argument n specifies the new length. The size may be extended or reduced. If n is more than the antique length and if sufficient area isn't always available subsequent to the antique area, the feature realloc ( ) may create a new location and all of the antique information are moved to the new location.
Question fifty four. Describe Static Memory Allocation And Dynamic Memory Allocation?
Static memory allocation: The compiler allocates the specified reminiscence space for a declared variable. By the usage of the deal with of operator, the reserved cope with 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 cost to a pointer variable is referred to as static memory allocation. Memory is assigned for the duration of compilation time. Dynamic reminiscence allocation: It uses features such as malloc ( ) or calloc ( ) to get memory dynamically. If these functions are used to get reminiscence dynamically and the values returned by way of these functions are assigned to pointer variables, such assignments are referred to as dynamic reminiscence allocation. Memory is assigned during run time.
Question 55. How Are Pointer Variables Initialized?
Pointer variable are initialized with the aid of one of the following two methods
Static memory allocation
Dynamic memory allocation
Question 56. What Is A Pointer Variable?
Answer :A pointer variable is a variable which could contain the deal with of some other variable or any legitimate address in the reminiscence.
Question 57. Differentiate Between Text And Binary Modes?
Streams can be classified into sorts: text streams and binary streams. Text streams are interpreted, with a maximum length of 255 characters. With textual content streams, carriage return/line feed combos are translated to the newline n man or woman and vice versa. Binary streams are uninterpreted and are handled one byte at a time without a translation of characters. Typically, a text circulate would be used for analyzing and writing popular textual content files, printing output to the display screen or printer, or receiving enter from the keyboard.
A binary text circulate might generally be used for studying and writing binary documents such as pictures or phrase processing files, studying mouse input, or studying and writing to the modem.
Question 58. How To Restore A Redirected Standard Stream?
The previous instance confirmed how you may redirect a popular circulate from within your software. But what if later on your application you wanted to repair the same old stream to its unique nation? By the use of the same old C library functions named dup() and fdopen(), you may restore a wellknown circulate which include stdout to its authentic country.
The dup() characteristic duplicates a file take care of. You can use the dup() feature to store the record deal with corresponding to the stdout fashionable stream. The fdopen() function opens a flow that has been duplicated with the dup() feature.
Question 59. How To Search For Data In A Linked List?
Unfortunately, the handiest manner to look a connected listing is with a linear search, because the most effective way a linked listing’s contributors can be accessed is sequentially. Sometimes it's miles faster to take the facts from a linked listing and shop it in a distinctive statistics structure in order that searches may be greater efficient.
Question 60. How To Sort A Linked List?
Answer :Both the merge type and the radix kind are precise sorting algorithms to apply for linked lists.
Question 61. What Do You Mean By Hashing?
To hash means to grind up, and that’s basically what hashing is all approximately. The heart of a hashing set of rules is a hash feature that takes your pleasant, neat statistics and grinds it into a few random-looking integer.
The concept in the back of hashing is that some information both has no inherent ordering (including photos) or is expensive to compare (along with photographs). If the records has no inherent ordering, you could’t perform evaluation searches.
If the records is luxurious to examine, the range of comparisons used even via a binary seek might be too many. So rather than searching at the facts themselves, you’ll condense (hash) the information to an integer (its hash cost) and keep all of the records with the same hash fee inside the same place. This venture is executed by the use of the hash fee as an index into an array. To search for an item, you genuinely hash it and have a look at all of the information whose hash values suit that of the statistics you’re seeking out. This technique significantly lessens the quantity of objects you have to study. If the parameters are installation with care and sufficient garage is available for the hash table, the variety of comparisons needed to locate an item can be made arbitrarily close to one.
One issue that influences the performance of a hashing implementation is the hash feature itself. It should preferably distribute records randomly all through the complete hash desk, to lessen the probability of collisions. Collisions arise while two distinct keys have the equal hash price. There are two ways to solve this hassle. In “open addressing,” the collision is resolved by way of the selecting of some other position within the hash table for the detail inserted later. When the hash table is searched, if the entry is not observed at its hashed function inside the table, the quest maintains checking till both the detail is observed or an empty function within the desk is observed.
The second technique of resolving a hash collision is known as “chaining.” In this method, a “bucket” or connected listing holds all the factors whose keys hash to the equal price. When the hash table is searched, the list need to be searched linearly.
Question sixty two. Which Is The Quickest Searching Method To Use?
A binary search, inclusive of bsearch() performs, is much faster than a linear seek. A hashing set of rules can offer even quicker searching. One specifically thrilling and fast method for looking is to keep the facts in a “digital trie.” A virtual trie offers the prospect of being capable of look for an object in basically a consistent quantity of time, impartial of what number of gadgets are within the information set.
A digital trie combines components of binary searching, radix looking, and hashing. The term “virtual trie” refers back to the information shape used to keep the items to be searched. It is a multilevel information structure that branches N ways at every stage.
Question sixty three. What Is The Easiest Sorting Method To Use?
The solution is the same old library feature qsort(). It’s the very best sort with the aid of a ways for several reasons:
It is already written.
It is already debugged.
It has been optimized as much as viable (normally).
Void qsort(void *buf, size_t num, size_t length, int (*comp)
(const void *ele1, const void *ele2));
Question sixty four. Which Is The Quickest Sorting Method To Use?
The answer relies upon on what you imply by means of quickest. For most sorting troubles, it just doesn’t count how short the type is due to the fact it's miles done once in a while or other operations take extensively greater time besides. Even in cases wherein sorting pace is of the essence, there's no one answer. It depends on no longer most effective the scale and nature of the information, but additionally the probably order. No set of rules is best in all instances.
There are three sorting methods in this creator’s “toolbox” which can be all very speedy and which are useful in unique situations. Those methods are brief sort, merge sort, and radix type.
The Quick Sort :The short type algorithm is of the “divide and overcome” kind. That means it works with the aid of reducing a sorting trouble into several easier sorting issues and solving every of them. A “dividing” fee is chosen from the enter information, and the facts is partitioned into 3 units: elements that belong earlier than the dividing price, the fee itself, and factors that come after the dividing value. The partitioning is completed by replacing factors which are inside the first set but belong inside the third with elements which might be in the 1/3 set however belong in the first Elements which are equal to the dividing element may be put in any of the 3 units—the algorithm will nevertheless work nicely.
The Merge Sort: The merge sort is a “divide and triumph over” type as well. It works by using thinking about the information to be looked after as a series of already-taken care of lists (inside the worst case, each list is one element long). Adjacent taken care of lists are merged into larger taken care of lists until there may be a unmarried sorted list containing all the elements. The merge sort is good at sorting lists and different data systems that aren't in arrays, and it can be used to sort things that don’t suit into reminiscence. It also may be applied as a stable sort.
The Radix Sort : The radix sort takes a list of integers and places every element on a smaller list, relying at the price of its least huge byte. Then the small lists are concatenated, and the manner is repeated for every greater full-size byte until the listing is looked after. The radix kind is easier to implement on constant-period data including ints.
Question sixty five. What Is The Benefit Of Using Const For Declaring Constants?
The advantage of using the const keyword is that the compiler might be capable of make optimizations primarily based at the information that the fee of the variable will no longer exchange. In addition, the compiler will try to ensure that the values gained’t be changed inadvertently.
Of course, the same blessings follow to #described constants. The cause to apply const in place of #define to outline a consistent is that a const variable can be of any kind (along with a struct, that may’t be represented by way of a #defined constant). Also, because a const variable is a real variable, it has an deal with that may be used, if needed, and it resides in simplest one area in reminiscence.
Question 66. Is It Acceptable To Declare/outline A Variable In A C Header?
A international variable that have to be accessed from more than one record can and need to be declared in a header document. In addition, any such variable must be described in one source document.
Variables need to now not be defined in header documents, because the header report may be included in multiple source documents, which might reason more than one definitions of the variable. The ANSI C trendy will allow more than one external definitions, provided that there's most effective one initialization. But because there’s honestly no gain to the use of this option, it’s possibly fine to keep away from it and preserve a higher degree of portability.
“Global” variables that don't ought to be accessed from multiple record have to be declared static and need to no longer appear in a header file.
Question 67. When Should A Type Cast Be Used?
There are two situations in which to use a type cast. The first use is to trade the type of an operand to an arithmetic operation so that the operation may be executed properly.
The second case is to forged pointer sorts to and from void * on the way to interface with capabilities that expect or return void hints. For example, the following line type casts the go back value of the call to malloc() to be a pointer to a foo shape.
Struct foo *p = (struct foo *) malloc(sizeof(struct foo));
Question sixty eight. How To Determine The Maximum Value That A Numeric Variable Can Hold?
For quintessential types, on a system that makes use of ’s supplement mathematics (which is just about any device you’re likely to use), a signed type can keep numbers from –2(wide variety of bits – 1) to +2(quantity of bits – 1) – 1. An unsigned kind can maintain values from 0 to +2(range of bits) – 1. For instance, a 16-bit signed integer can maintain numbers from –2^15 (–32768) to +2^15 – 1 (32767).
Question 69. Can A Variable Be Both Const And Volatile?
Yes. The const modifier manner that this code cannot exchange the cost of the variable, but that does not suggest that the value can not be changed by way of method outside this code. For instance, in the example in FAQ 8, the timer shape become accessed thru a unstable const pointer. The feature itself did no longer change the fee of the timer, so it changed into declared const. However, the fee turned into modified via hardware on the laptop, so it become declared unstable. If a variable is each const and unstable, the two modifiers can seem in both order.
Question 70. When Does The Register Modifier Be Used? Does It Really Help?
The check in modifier tips to the compiler that the variable could be heavily used and should be saved within the CPU’s registers, if viable, so that it is able to be accessed faster. There are numerous restrictions on using the sign in modifier.
First, the variable have to be of a kind that may be held in the CPU’s sign in. This usually means a unmarried price of a length much less than or same to the size of an integer. Some machines have registers which could keep floating-factor numbers as well. Second, because the variable may not be saved in reminiscence, its address can't be excited by the unary & operator. An try and achieve this is flagged as an error with the aid of the compiler. Some additional rules have an effect on how beneficial the register modifier is. Because the variety of registers is restricted, and due to the fact some registers can keep best positive styles of statistics (which includes tips or floating-point numbers), the range and types of sign in modifiers with the intention to actually have any impact are dependent on what machine this system will run on. Any extra sign in modifiers are silently neglected with the aid of the compiler.
Also, in a few instances, it'd surely be slower to hold a variable in a sign up because that register then turns into unavailable for different functions or due to the fact the variable isn’t used sufficient to justify the overhead of loading and storing it.
So whilst need to the sign up modifier be used? The answer is by no means, with most modern compilers. Early C compilers did now not preserve any variables in registers unless directed to accomplish that, and the sign up modifier turned into a valuable addition to the language. C compiler layout has advanced to the point, however, where the compiler will generally make better selections than the programmer approximately which variables should be saved in registers. In reality, many compilers sincerely ignore the sign up modifier, which is perfectly felony, due to the fact it's far only a touch and now not a directive.