C语言鄙视题英文版 超级飞侠英文版主题曲
When writingyour C program, you can include files in two ways.
The first way is to surround the file you want to include with theangled brackets <</B> and>. This method of inclusiontells the preprocessor to look for the file in the predefineddefault location. This predefined default location is often anINCLUDE environment variable that denotes the path to yourinclude files. For instance, given the INCLUDEvariable
INCLUDE=C:COMPILERINCLUDE;S:SOURCEHEADERS;
using the #include <>version of file inclusion, the compiler first checks theC:COMPILERINCLUDE directory for the specified file. If thefile is not found there, the compiler then checks theS:SOURCEHEADERS 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 toinclude with double quotation marks. This method of inclusion tellsthe preprocessor to look for the file in the current directoryfirst, then look for it in the predefined locations you have setup. Using the #include "" fileversion of file inclusion and applying it to the preceding example,the preprocessor first checks the current directory for thespecified file. If the file is not found in the current directory,the C:COMPILERINCLUDE directory is searched. If the fileis still not found, the preprocessor checks theS:SOURCEHEADERS directory.
The #include <> methodof file inclusion is often used to include standard headers such asstdio.h or stdlib.h. This is because these headers are rarely (ifever) modified, and they should always be read from your compiler'sstandard include file directory.
The #include "" file method offile inclusion is often used to include nonstandard header filesthat you have created for use in your program. This is becausethese headers are often modified in the current directory, and youwill want the preprocessor to use your newly modified version ofthe header rather than the older, unmodified version.
2. What is the benefit of using anenum rather than a#define constant?
The use of anenumeration constant (enum)has many advantages over using the traditional symbolic constantstyle of #define. Theseadvantages include a lower maintenance requirement, improvedprogram readability, and better debugging capability.
1) The first advantage is that enumerated constants are generatedautomatically by the compiler. Conversely, symbolic constants mustbe manually assigned values by the programmer.
For instance, if you had an enumerated constant type for errorcodes that could occur in your program, your enum definition could look something likethis:
enum Error_Code {
OUT_OF_MEMORY,
INSUFFICIENT_DISK_SPACE,
LOGIC_ERROR,
FILE_NOT_FOUND
};
In the preceding example, OUT_OF_MEMORY is automatically assignedthe value of 0 (zero) by the compiler because it appears first inthe definition. The compiler then continues to automatically assignnumbers to the enumerated constants, making INSUFFICIENT_DISK_SPACE equal to 1,LOGIC_ERROR equal to 2, andFILE_NOT_FOUND equal to 3, soon.
If you were to approach the same example by using symbolicconstants, 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 thesame result: four constants assigned numeric values to representerror codes. Consider the maintenance required, however, if youwere to add two constants to represent the error codes DRIVE_NOT_READY and CORRUPT_FILE. Using the enumerationconstant method, you simply would put these two constants anywherein the enum definition. Thecompiler would generate two unique values for these constants.Using the symbolic constant method, you would have to manuallyassign two new numbers to these constants. Additionally, you wouldwant to ensure that the numbers you assign to these constants areunique.
2) Another advantage of using the enumeration constant method isthat your programs are more readable and thus can be understoodbetter by others who might have to update your program later.
3) A third advantage to using enumeration constants is that somesymbolic debuggers can print the value of an enumeration constant.Conversely, most symbolic debuggers cannot print the value of asymbolic constant. This can be an enormous help in debugging yourprogram, because if your program is stopped at a line that uses anenum, you can simply inspectthat constant and instantly know its value. On the other hand,because most debuggers cannot print #define values, you would most likely haveto search for that value by manually looking it up in a headerfile.
3. How can I open a file so that otherprograms can update it at the same time?
Your Ccompiler library contains a low-level file function calledsopen() that can be used toopen a file in shared mode. Beginning with DOS 3.0, files could beopened in shared mode by loading a special program namedSHARE.EXE. Shared mode, as the name implies, allows a fileto be shared with other programs as well as your own.
Using this function, you can allow other programs that are runningto update the same file you are updating.
The sopen() function takesfour parameters: a pointer to the filename you want to open, theoperational mode you want to open the file in, the file sharingmode to use, and, if you are creating a file, the mode to createthe file in. The second parameter of the sopen() function, usually referred to asthe operation flag parameter, can have the following valuesassigned to it:
Constant Description
O_APPEND Appends all writes tothe end of the file
O_BINARY Opens the file inbinary (untranslated) mode
O_CREAT Ifthe file does not exist, it is created
O_EXCL Ifthe O_CREAT flag is used andthe file exists, returns an error
O_RDONLY Opens the file inread-only mode
O_RDWR Opens the file for reading and writing
O_TEXT Opens the file in text (translated) mode
O_TRUNC Opens an existing file and writes over its contents
O_WRONLY Opens the file inwrite-only mode
The third parameter of the sopen() function, usually referred to asthe sharing flag, can have the following values assigned toit:
Constant Description
SH_COMPAT No other program canaccess the file
SH_DENYRW No other program canread from or write to the file
SH_DENYWR No other program canwrite to the file
SH_DENYRD No other program canread from the file
SH_DENYNO Any program can readfrom or write to the file
If the sopen() function issuccessful, it returns a non-negative number that is the file'shandle. If an error occurs, 1 is returned, and the global variableerrno is set to one of the following values:
Constant Description
ENOENT Fileor path not found
EMFILE Nomore file handles are available
EACCES Permission denied to access file
EINVACC Invalid access code
4. What is hashing?
To hash meansto grind up, and that's essentially what hashing is all about. Theheart of a hashing algorithm is a hash function that takes yournice, neat data and grinds it into some random-lookinginteger.
The idea behind hashing is that some data either has no inherentordering (such as images) or is expensive to compare (such asimages). If the data has no inherent ordering, you can't performcomparison searches.
If the data is expensive to compare, the number of comparisons usedeven by a binary search might be too many. So instead of looking atthe data themselves, you'll condense (hash) the data to an integer(its hash value) and keep all the data with the same hash value inthe same place. This task is carried out by using the hash value asan index into an array.
To search for an item, you simply hash it and look at all the datawhose hash values match that of the data you're looking for. Thistechnique greatly lessens the number of items you have to look at.If the parameters are set up with care and enough storage isavailable for the hash table, the number of comparisons needed tofind an item can be made arbitrarily close to one.
One aspect that affects the efficiency of a hashing implementationis the hash function itself. It should ideally distribute datarandomly throughout the entire hash table, to reduce the likelihoodof collisions. Collisions occur when two different keys have thesame hash value. There are two ways to resolve this problem.
In open addressing, the collision is resolved by thechoosing of another position in the hash table for the elementinserted later. When the hash table is searched, if the entry isnot found at its hashed position in the table, the search continueschecking until either the element is found or an empty position inthe table is found.
The second method of resolving a hash collision is calledchaining. In this method, a bucket or linked list holds allthe elements whose keys hash to the same value. When the hash tableis searched, the list must be searched linearly.
5. What is the quickest sorting methodto use?
The answerdepends on what you mean by quickest. For most sorting problems, itjust doesn't matter how quick the sort is because it is doneinfrequently or other operations take significantly more timeanyway. Even in cases in which sorting speed is of the essence,there is no one answer. It depends on not only the size and natureof the data, but also the likely order. No algorithm is best in allcases.
There are three sorting methods in this author's toolbox that areall very fast and that are useful in different situations. Thosemethods are quick sort, merge sort, and radix sort.
The Quick Sort: The quick sort algorithm is of the divideand conquer type. That means it works by reducing a sorting probleminto several easier sorting problems and solving each of them. Adividing value is chosen from the input data, and the data ispartitioned into three sets: elements that belong before thedividing value, the value itself, and elements that come after thedividing value. The partitioning is performed by exchangingelements that are in the first set but belong in the third withelements that are in the third set but belong in the first Elementsthat are equal to the dividing element can be put in any of thethree setsthe algorithm will still work properly.
The Merge Sort: The merge sort is a divide and conquer sortas well. It works by considering the data to be sorted as asequence of already-sorted lists (in the worst case, each list isone element long). Adjacent sorted lists are merged into largersorted lists until there is a single sorted list containing all theelements. The merge sort is good at sorting lists and other datastructures that are not in arrays, and it can be used to sortthings that don't fit into memory. It also can be implemented as astable sort.
The Radix Sort: The radix sort takes a list of integers andputs each element on a smaller list, depending on the value of itsleast significant byte. Then the small lists are concatenated, andthe process is repeated for each more significant byte until thelist is sorted. The radix sort is simpler to implement onfixed-length data such as ints.
6. When should the volatile modifier be used?
The volatile modifier is a directive to thecompiler's optimizer that operations involving this variable shouldnot be optimized in certain ways. There are two special cases inwhich use of the volatilemodifier is desirable. The first case involves memory-mappedhardware (a device such as a graphics adaptor that appears to thecomputer's hardware as if it were part of the computer's memory),and the second involves shared memory (memory used by two or moreprograms running simultaneously).
Most computers have a set of registers that can be accessed fasterthan the computer's main memory. A good compiler will perform akind of optimization called redundant load and storeremoval. The compiler looks for places in the code where it caneither remove an instruction to load data from memory because thevalue is already in a register, or remove an instruction to storedata to memory because the value can stay in a register until it ischanged again anyway.
If a variable is a pointer to something other than normal memory,such as memory-mapped ports on a peripheral, redundant load andstore optimizations might be detrimental. For instance, here's apiece of code that might be used to time some operation:
time_t time_addition(volatile const struct timer* t,int a) {
int n;
int x;
time_t then;
x = 0;
then = t->value;
for (n = 0; n < 1000; n++) {
x = x + a;
}
return t->value - then;
}
In this code, the variable t->value is actually a hardware counterthat is being incremented as time passes. The function adds thevalue of a to x 1000 times, and it returns the amountthe timer was incremented by while the 1000 additions were beingperformed. Without the volatile modifier, a clever optimizermight assume that the value of t does not change during the execution ofthe function, because there is no statement that explicitly changesit. In that case, there's no need to read it from memory a secondtime and subtract it, because the answer will always be 0. Thecompiler might therefore optimize the function by making it alwaysreturn 0.
If a variable points to data in shared memory, you also don't wantthe compiler to perform redundant load and store optimizations.Shared memory is normally used to enable two programs tocommunicate with each other by having one program store data in theshared portion of memory and the other program read the sameportion of memory. If the compiler optimizes away a load or storeof shared memory, communication between the two programs will beaffected.
7. When should the register modifier be used? Does it reallyhelp?
Theregister modifier hints to thecompiler that the variable will be heavily used and should be keptin the CPU's registers, if possible, so that it can be accessedfaster.
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'sregister. This usually means a single value of a size less than orequal to the size of an integer. Some machines have registers thatcan hold floating-point numbers as well.
Second, because the variable might not be stored in memory, itsaddress cannot be taken with the unary & operator. An attempt to do so isflagged as an error by the compiler. Some additional rules affecthow useful the registermodifier is. Because the number of registers is limited, andbecause some registers can hold only certain types of data (such aspointers or floating-point numbers), the number and types ofregister modifiers that willactually have any effect are dependent on what machine the programwill run on. Any additional register modifiers are silently ignored bythe compiler.
Also, in some cases, it might actually be slower to keep a variablein a register because that register then becomes unavailable forother purposes or because the variable isn't used enough to justifythe overhead of loading and storing it.
So when should the registermodifier be used? The answer is never, with most modern compilers.Early C compilers did not keep any variables in registers unlessdirected to do so, and the register modifier was a valuableaddition to the language. C compiler design has advanced to thepoint, however, where the compiler will usually make betterdecisions than the programmer about which variables should bestored in registers.
In fact, many compilers actually ignore the register modifier, which is perfectlylegal, because it is only a hint and not a directive.
8. What is page thrashing?
Someoperating systems (such as UNIX or Windows in enhanced mode) usevirtual memory. Virtual memory is a technique for making a machinebehave as if it had more memory than it really has, by using diskspace to simulate RAM (random-access memory). In the 80386 andhigher Intel CPU chips, and in most other modern microprocessors(such as the Motorola 68030, Sparc, and Power PC), exists a pieceof hardware called the Memory Management Unit, or MMU.
The MMU treats memory as if it were composed of a series of pages.A page of memory is a block of contiguous bytes of a certain size,usually 4096 or 8192 bytes. The operating system sets up andmaintains a table for each running program called the ProcessMemory Map, or PMM. This is a table of all the pages of memory thatprogram can access and where each is really located.
Every time your program accesses any portion of memory, the address(called a virtual address) is processed by the MMU. The MMU looksin the PMM to find out where the memory is really located (calledthe physical address). The physical address can be any location inmemory or on disk that the operating system has assigned for it. Ifthe location the program wants to access is on disk, the pagecontaining it must be read from disk into memory, and the PMM mustbe updated to reflect this action (this is called a pagefault).
Because accessing the disk is so much slower than accessing RAM,the operating system tries to keep as much of the virtual memory aspossible in RAM. If you're running a large enough program (orseveral small programs at once), there might not be enough RAM tohold all the memory used by the programs, so some of it must bemoved out of RAM and onto disk (this action is called paging out).The operating system tries to guess which areas of memory aren'tlikely to be used for a while (usually based on how the memory hasbeen used in the past). If it guesses wrong, or if your programsare accessing lots of memory in lots of places, many page faultswill occur in order to read in the pages that were paged out.Because all of RAM is being used, for each page read in to beaccessed, another page must be paged out. This can lead to morepage faults, because now a different page of memory has been movedto disk.
The problem of many page faults occurring in a short time, calledpage thrashing, can drastically cut the performance of a system.Programs that frequently access many widely separated locations inmemory are more likely to cause page thrashing on a system. So isrunning many small programs that all continue to run even when youare not actively using them. To reduce page thrashing, you can runfewer programs simultaneously. Or you can try changing the way alarge program works to maximize the capability of the operatingsystem to guess which pages won't be needed. You can achieve thiseffect by caching values or changing lookup algorithms in largedata structures, or sometimes by changing to a memory allocationlibrary which provides an implementation of malloc() that allocatesmemory more efficiently. Finally, you might consider adding moreRAM to the system to reduce the need to page out.
9. How can you determine the size of anallocated portion of memory?
You can't,really. free() can , butthere's no way for your program to know the trick free() uses. Even if you disassemble thelibrary and discover the trick, there's no guarantee the trickwon't change with the next release of the compiler.
10. Can static variables be declared in a headerfile?
You can'tdeclare a static variablewithout defining it as well (this is because the storage classmodifiers static andextern are mutuallyexclusive). A static variablecan be defined in a header file, but this would cause each sourcefile that included the header file to have its own private copy ofthe variable, which is probably not what was intended.
11. How do you override a definedmacro?
You can usethe #undef preprocessordirective to undefine (override) a previously defined macro.
12. How can you check to see whether asymbol is defined?
You can use the#ifdef and #ifndef preprocessor directives to checkwhether a symbol has been defined (#ifdef) or whether it has not been defined(#ifndef).
Can you define which header file to include at compile time? Yes.This can be done by using the #if, #else, and #endif preprocessor directives. Forexample, certain compilers use different names for header files.One such case is between Borland C++, which uses the header filealloc.h, and Microsoft C++, which uses the header filemalloc.h. Both of these headers serve the same purpose, andeach contains roughly the same definitions. If, however, you arewriting a program that is to support Borland C++ and Microsoft C++,you must define which header to include at compile time. Thefollowing example shows how this can be done:
#ifdef __BORLANDC__
#include
#else
#include
#endif
13. Can a variable be bothconst and volatile?
Yes. Theconst modifier means that thiscode cannot change the value of the variable, but that does notmean that the value cannot be changed by means outside this code.For instance, in the example in FAQ 8, the timer structure wasaccessed through a volatileconst pointer. The function itself did not change thevalue of the timer, so it was declared const. However, the value was changed byhardware on the computer, so it was declared volatile. If a variable is bothconst and volatile, the two modifiers can appear ineither order.
14. Can include files benested?
Answer Yes.Include files can be nested any number of times. As long as you useprecautionary measures, you can avoid including the same filetwice. In the past, nesting header files was seen as badprogramming practice, because it complicates the dependencytracking function of the MAKE program and thus slows downcompilation. Many of today's popular compilers make up for thisdifficulty by implementing a concept called precompiled headers, inwhich all headers and associated dependencies are stored in aprecompiled state.
Many programmers like to create a custom header file that has#include statements for everyheader needed for each module. This is perfectly acceptable and canhelp avoid potential problems relating to #include files, such as accidentallyomitting an #include file in amodule.
15. Write the equivalent expression forx%8?
x&7
16. When does the compiler notimplicitly generate the address of the first element of anarray?
Whenever anarray 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 thefirst element of an array.
17. What is the benefit of using#define to declare aconstant?
Using the#define method of declaring aconstant enables you to declare a constant in one place and use itthroughout your program. This helps make your programs moremaintainable, because you need to maintain only the #define statement and not severalinstances of individual constants throughout your program.
For instance, if your program used the value of pi (approximately3.14159) several times, you might want to declare a constant for pias follows:
#define PI 3.14159
Using the #define method ofdeclaring a constant is probably the most familiar way of declaringconstants to traditional C programmers. Besides being the mostcommon method of declaring constants, it also takes up the leastmemory. Constants defined in this manner are simply placed directlyinto your source code, with no variable space allocated in memory.Unfortunately, this is one reason why most debuggers cannot inspectconstants created using the #define method.
18. How can I search for data in alinked list?
Unfortunately, the only way to search a linked list is with alinear search, because the only way a linked list's members can beaccessed is sequentially. Sometimes it is quicker to take the datafrom a linked list and store it in a different data structure sothat searches can be more efficient.
19. Why should we assign NULL to the elements (pointer) afterfreeing them?
This isparanoia based on long experience. After a pointer has been freed,you can no longer use the pointed-to data. The pointer is said todangle; it doesn't point at anything useful. If you NULL out or zero out a pointer immediatelyafter freeing it, your program can no longer get in trouble byusing that pointer. True, you might go indirect on the null pointerinstead, but that's something your debugger might be able to helpyou with immediately. Also, there still might be copies of thepointer that refer to the memory that has been deallocated; that'sthe nature of C. Zeroing out pointers after freeing them won'tsolve all problems;
20. What is a null pointer assignmenterror? What are bus errors, memory faults, and coredumps?
These are allserious errors, symptoms of a wild pointer or subscript.
Null pointer assignment is a message you might get when an MS-DOSprogram finishes executing. Some such programs can arrange for asmall amount of memory to be available "where the NULL pointer points to (so to speak). Ifthe program tries to write to that area, it will overwrite the dataput there by the compiler.
When the program is done, code generated by the compiler examinesthat area. If that data has been changed, the compiler-generatedcode 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 assignmentmessage, what part of your program is responsible for the error.Some debuggers, and some compilers, can give you more help infinding the problem.
Bus error: core dumped and Memory fault: core dumped are messagesyou might see from a program running under UNIX. They're moreprogrammer friendly. Both mean that a pointer or an array subscriptwas wildly out of bounds. You can get these messages on a read oron 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 thetime the program was running. With the help of a debugger, you canuse 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 inthe right direction. If you don't have write permission in thecurrent directory, you won't get a core file, or the core dumpedmessage.
21. When should a type cast beused?
There are twosituations in which to use a type cast. The first use is to changethe type of an operand to an arithmetic operation so that theoperation will be performed properly.
The second case is to cast pointer types to and from void * in order to interface withfunctions that expect or return void pointers. For example, the followingline 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));
22. What is a nullpointer?
There aretimes when it's necessary to have a pointer that doesn't point toanything. The macro NULL,defined in stdlib.h, has a value that's guaranteed to bedifferent from any valid pointer. NULL is a literal zero, possibly cast tovoid* or char*. Some people, notably C++programmers, prefer to use 0rather than NULL.
The null pointer is used in three ways:
1) To stop indirection in a recursive data structure
2) As an error value
3) As a sentinel value
23. What is the difference between astring copy (strcpy) and amemory copy (memcpy)? Whenshould each be used?
Thestrcpy() function is designedto work exclusively with strings. It copies each byte of the sourcestring to the destination string and stops when the terminatingnull character has been moved. On the other hand, the memcpy() function is designed to work withany 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 sourceto the destination.
24. How can I convert a string to anumber?
The standardC library provides several functions for converting strings tonumbers of all formats (integers, longs, floats, and so on) andvice versa.
The following functions can be used to convert strings tonumbers:
Function Name Purpose
atof() Converts a string to adouble-precision floating-point value.
atoi() Converts a string to aninteger.
atol() Converts a string to a longinteger.
strtod() Converts a string to a double-precisionfloating-point value and reports any leftover numbers that couldnot be converted.
strtol() Converts a string to a long integer and reportsany leftover numbers that could not be converted.
strtoul() Converts a string to an unsigned long integerand reports any leftover numbers that could not be converted.
25. How can I convert a number to astring?
The standardC library provides several functions for converting numbers of allformats (integers, longs, floats, and so on) to strings and viceversa. The following functions can be used to convert integers tostrings:
Function Name Purpose
itoa() Converts an integer value toa string.
ltoa() Converts a long integer valueto a string.
ultoa() Converts an unsigned long integer value to astring.
The following functions can be used to convert floating-pointvalues to strings:
Function Name Purpose
ecvt() Converts a double-precision floating-point valueto a string without an embedded decimal point.
fcvt() Same as ecvt(), but forces the precision to aspecified number of digits.
gcvt() Converts a double-precision floating-point valueto a string with an embedded decimal point.
26. Is it possible to execute code evenafter the program exits the main() function?
The standardC library provides a function named atexit() that can be used to performcleanup operations when your program terminates. You can set up aset of functions you want to perform automatically when yourprogram exits by passing function pointers to the atexit() function.
27. What is the stack?
The stack iswhere all the functions' local (auto) variables are created. The stackalso contains some information used to call and return fromfunctions.
A stack trace is a list of which functions have been called, basedon this information. When you start using a debugger, one of thefirst things you should learn is how to get a stack trace.
The stack is very inflexible about allocating memory, everythingmust be deallocated in exactly the reverse order it was allocatedin. For implementing function calls, that is all that's needed.Allocating memory off the stack is extremely efficient. One of thereasons C compilers generate such good code is their heavy use of asimple stack.
There used to be a C function that any programmer could use forallocating memory off the stack. The memory was automaticallydeallocated when the calling function returned. This was adangerous function to call; it's not available anymore.
28. How do you print anaddress?
The safestway is to use printf() (orfprintf() or sprintf()) with the %P specification. That prints a voidpointer (void*). Differentcompilers might print a pointer with different formats. Yourcompiler will pick a format that's right for yourenvironment.
If you have some other kind of pointer (not a void*) and you want to be very safe, castthe pointer to a void*:
printf("%Pn", (void*)buffer);
29. Can a file other than a .hfile be included with #include?
Thepreprocessor 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 inyour precompiled program. It is, however, unusual programmingpractice 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 filesyou are going to include. This method makes it easier for you andothers to identify which files are being used for preprocessingpurposes. For instance, someone modifying or debugging your programmight not know to look at the macros.inc file for macrodefinitions. That person might try in vain by searching all fileswith .h extensions and come up empty. If your file had beennamed macros.h, the search would have included themacros.h file, and the searcher would have been able to seewhat macros you defined in it.
30. What is Preprocessor?
Thepreprocessor is used to modify your program according to thepreprocessor directives in your source code. Preprocessordirectives (such as #define)give the preprocessor specific instructions on how to modify yoursource code. The preprocessor reads in all of your include filesand the source code you are compiling and creates a preprocessedversion of your source code. This preprocessed version has all ofits macros and constant symbols replaced by their correspondingcode and value assignments. If your source code contains anyconditional preprocessor directives (such as #if), the preprocessor evaluates thecondition and modifies your source code accordingly.
The preprocessor contains many features that are powerful to use,such as creating macros, performing conditional compilation,inserting predefined environment variables into your code, andturning compiler features on and off. For the professionalprogrammer, in-depth knowledge of the features of the preprocessorcan be one of the keys to creating fast, efficient programs.
31. How can you restore a redirectedstandard stream?
The precedingexample showed how you can redirect a standard stream from withinyour program. But what if later in your program you wanted torestore the standard stream to its original state? By using thestandard C library functions named dup() and fdopen(), you can restore a standardstream such as stdout to its original state.
The dup() function duplicatesa file handle. You can use the dup() function to save the file handlecorresponding to the stdout standard stream. Thefdopen() function opens astream that has been duplicated with the dup() function.
32. What is the heap?
The heap iswhere malloc(), calloc(), and realloc() get memory.
Getting memory from the heap is much slower than getting it fromthe stack. On the other hand, the heap is much more flexible thanthe stack. Memory can be allocated at any time and deallocated inany order. Such memory isn't deallocated automatically; you have tocall free().
Recursive data structures are almost always implemented with memoryfrom the heap. Strings often come from there too, especiallystrings that could be very long at runtime. If you can keep data ina local variable (and allocate it from the stack), your code willrun faster than if you put the data on the heap. Sometimes you canuse 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 theprogram ends. That's great if you remember to deallocate it whenyou're done. If you forget, it's a problem. A memory leak is someallocated memory that's no longer needed but isn't deallocated. Ifyou have a memory leak inside a loop, you can use up all the memoryon the heap and not be able to get any more. (When that happens,the allocation functions return a null pointer.) In someenvironments, if a program doesn't deallocate everything itallocated, memory stays unavailable even after the programends.
33. How do you use a pointer to afunction?
The hardestpart about using a pointer-to-function is declaring it.
Consider an example. You want to create a pointer, pf, that points to the strcmp() function.
The strcmp() function isdeclared in this way:
int strcmp(const char*, constchar*)
To set up pf to point to thestrcmp() function, you want adeclaration that looks just like the strcmp() function's declaration, but thathas *pf rather thanstrcmp:
int (*pf)(const char*, constchar*);
After you've gotten the declaration of pf, you can #include and assign the address ofstrcmp() to pf: pf = strcmp;
34. What is the purpose of realloc()?
The function realloc(ptr,n) uses two arguments. The first argument ptr is a pointer to a block of memory forwhich the size is to be altered. The second argument n specifies the new size. The size may beincreased or decreased. If nis greater than the old size and if sufficient space is notavailable subsequent to the old region, the function realloc() may create a new region and allthe old data are moved to the newregion.
35. What is the purpose of main() function?
The functionmain() invokes other functionswithin it. It is the first function to be called when the programstarts execution.
- It is the starting function
- It returns an int value tothe 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 functionmain() is reached.
- It has two arguments 1) argument count and 2) argument vector(represents strings passed).
- Any user-defined name can also be used as parameters formain() instead of argc and argv
36. why n++ executes faster than n+1?
Theexpression n++ requires asingle machine instruction such as INR to carry out theincrement operation, whereas n+1 requires more instructions to carryout this operation.
37. What will the preprocessor do for aprogram?
The Cpreprocessor is used to modify your program according to thepreprocessor directives in your source code. A preprocessordirective is a statement (such as #define) that gives the preprocessorspecific instructions on how to modify your source code. Thepreprocessor is invoked as the first part of your compilerprogram's compilation step. It is usually hidden from theprogrammer because it is run automatically by the compiler.
The preprocessor reads in all of your include files and the sourcecode you are compiling and creates a preprocessed version of yoursource code. This preprocessed version has all of its macros andconstant symbols replaced by their corresponding code and valueassignments. If your source code contains any conditionalpreprocessor directives (such as #if), the preprocessor evaluates thecondition and modifies your source code accordingly.
38. What is the benefit of usingconst for declaringconstants?
The benefitof using the const keyword isthat the compiler might be able to make optimizations based on theknowledge that the value of the variable will not change. Inaddition, the compiler will try to ensure that the values won't bechanged inadvertently.
Of course, the same benefits apply to #defined constants. The reason to useconst rather than #define todefine a constant is that a const variable can be of any type (such asa struct, which can't berepresented by a #definedconstant). Also, because a const variable is a real variable, it hasan address that can be used, if needed, and it resides in only oneplace in memory.
39. What is the easiest sorting methodto use?
The answer isthe standard library function qsort(). It's the easiest sort by far forseveral 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_tsize, int (*comp)(const void *ele1, const void*ele2));
40. How many levels of pointers can youhave?
The answer dependson what you mean by levels of pointers. If you mean how many levelsof indirection can you have in a single declaration? the answer isat 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;
The ANSI C standard says all compilers must handle at least 12levels. Your compiler might support more.
41. Is it better to use a macro or afunction?
The answerdepends on the situation you are writing code for. Macros have thedistinct advantage of being more efficient (and faster) thanfunctions, because their corresponding code is inserted directlyinto your source code at the point where the macro is called. Thereis no overhead involved in using a macro like there is in placing acall to a function. However, macros are generally small and cannothandle large, complex coding constructs. A function is more suitedfor this type of situation. Additionally, macros are expandedinline, which means that the code is replicated for each occurrenceof a macro. Your code therefore could be somewhat larger when youuse macros than if you were to use functions.
Thus, the choice between using a macro and using a function is oneof deciding between the tradeoff of faster program speed versussmaller program size. Generally, you should use macros to replacesmall, repeatable code sections, and you should use functions forlarger coding tasks that might require several lines of code.
42. What are the standard predefinedmacros?
The ANSI Cstandard defines six predefined macros for use in the Clanguage:
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.
__STDC__ Isset to 1 if you are enforcing strict ANSI C conformity.
__cplusplus Is defined if youare compiling a C++ program.
43. What is a const pointer?
The access modifierkeyword const is a promise theprogrammer makes to the compiler that the value of a variable willnot be changed after it is initialized. The compiler will enforcethat promise as best it can by not enabling the programmer to writecode which modifies a variable that has been declared const.
A const pointer, or morecorrectly, a pointer to const,is a pointer which points to data that is const (constant, or unchanging). A pointerto const is declared byputting the word const at thebeginning of the pointer declaration. This declares a pointer whichpoints to data that can't be modified. The pointer itself can bemodified. The following example illustrates some legal and illegaluses of a const pointer:
const char *str = hello;
char c = *str
str++;
*str = 'a';
str[1] = 'b';
44. What is a pragma?
The#pragma preprocessor directiveallows each compiler to implement compiler-specific features thatcan be turned on and off with the #pragma statement. For instance, yourcompiler might support a feature called loop optimization. Thisfeature can be invoked as a command-line option or as a#pragma directive.
To implement this option using the #pragma directive, you would put thefollowing line into your code:
#pragma loop_opt(on)
Conversely, you can turn off loop optimization by inserting thefollowing line into your code:
#pragma loop_opt(off)
45. What is #line used for?
The#line preprocessor directiveis used to reset the values of the __LINE__ and __FILE__ symbols, respectively. Thisdirective is commonly used in fourth-generation languages thatgenerate C language source files.
46. What is the difference between textand binary modes?
Streams canbe classified into two types: text streams and binary streams. Textstreams are interpreted, with a maximum length of 255 characters.With text streams, carriage return/line feed combinations aretranslated to the newline character and vice versa. Binary streamsare uninterpreted and are treated one byte at a time with notranslation of characters. Typically, a text stream would be usedfor reading and writing standard text files, printing output to thescreen or printer, or receiving input from the keyboard.
A binary text stream would typically be used for reading andwriting binary files such as graphics or word processing documents,reading mouse input, or reading and writing to the modem.
47. How do you determine whether to usea stream function or a low-level function?
Streamfunctions such as fread() andfwrite() are buffered and aremore efficient when reading and writing text or binary data tofiles. You generally gain better performance by using streamfunctions rather than their unbuffered low-level counterparts suchas read() and write().
In multi-user environments, however, when files are typicallyshared and portions of files are continuously being locked, readfrom, written to, and unlocked, the stream functions do not performas well as the low-level functions. This is because it is hard tobuffer a shared file whose contents are constantly changing.Generally, you should always use buffered stream functions whenaccessing nonshared files, and you should always use the low-levelfunctions when accessing shared files
48. What is static memory allocationand dynamic memory allocation?
Staticmemory allocation: The compiler allocates the required memoryspace for a declared variable. By using the address of operator,the reserved address is obtained and this address may be assignedto a pointer variable. Since most of the declared variable havestatic memory, this way of assigning pointer value to a pointervariable is known as static memory allocation. Memory is assignedduring compilation time.
Dynamic memory allocation: It uses functions such asmalloc() or calloc() to get memory dynamically. Ifthese functions are used to get memory dynamically and the valuesreturned by these functions are assingned to pointer variables,such assignments are known as dynamic memory allocation. Memory isassined during run time.
49. When should a far pointer beused?
Sometimes youcan get away with using a small memory model in most of a givenprogram. There might be just a few things that don't fit in yoursmall data and code segments. When that happens, you can useexplicit far pointers and function declarations to get at the restof memory. A far function can be outside the 64KB segment mostfunctions are shoehorned into for a small-code model. (Often,libraries are declared explicitly far, so they'll work no matterwhat code model the program uses.) A far pointer can refer toinformation outside the 64KB data segment. Typically, such pointersare used with farmalloc() andsuch, to manage a heap separate from where all the rest of the datalives. If you use a small-data, large-code model, you shouldexplicitly make your function pointers far.
50. What is the difference between farand near?
Somecompilers for PC compatibles use two types of pointers. nearpointers are 16 bits long and can address a 64KB range. farpointers are 32 bits long and can address a 1MB range.
Near pointers operate within a 64KB segment. There's one segmentfor function addresses and one segment for data. far pointers havea 16-bit base (the segment address) and a 16-bit offset. The baseis multiplied by 16, so a far pointer is effectively 20 bits long.Before you compile your code, you must tell the compiler whichmemory model to use. If you use a smallcode memory model, nearpointers 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 functionaddresses. You'll get near pointers with a small data model, andfar pointers with a large data model. These are just the defaults;you can declare variables and functions as explicitly near orfar.
Far pointers are a little slower. Whenever one is used, the code ordata segment register needs to be swapped out. far pointers alsohave odd semantics for arithmetic and comparison. For example, thetwo far pointers in the preceding example point to the sameaddress, but they would compare as different! If your program fitsin a small-data, small-code memory model, your life will beeasier.
51. When would you use a pointer to afunction?
Pointers tofunctions are interesting when you pass them to other functions. Afunction that takes function pointers says, in effect, Part of whatI do can be customized. Give me a pointer to a function, and I'llcall it when that part of the job needs to be done. That functioncan do its part for me. This is known as a callback. It's used alot in graphical user interface libraries, in which the style of adisplay is built into the library but the contents of the displayare part of the application.
As a simpler example, say you have an array of character pointers(char*), and you want to sortit by the value of the strings the character pointers point to. Thestandard qsort() function usesfunction 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.
52. How are pointer variablesinitialized?
Pointervariable are initialized by one of the following two ways
- Static memory allocation
- Dynamic memory allocation
53. How can you avoid including aheader more than once?
One easy techniqueto avoid multiple inclusions of the same header is to use the#ifndef and #define preprocessor directives. When youcreate a header for your program, you can #define a symbolic name that is unique tothat header. You can use the conditional preprocessor directivenamed #ifndef to check whetherthat symbolic name has already been assigned. If it is assigned,you should not include the header, because it has already beenpreprocessed. If it is not defined, you should define it to avoidany further inclusions of the header. The following headerillustrates this technique:
#ifndef XXXXX.H
#define XXXXX.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 tosee whether XXXXX.H has beendefined. If it hasn't been defined, the header has not beenincluded yet, and the XXXXX.Hsymbolic name is defined. Then, the rest of the header is parseduntil the last #endif isencountered, signaling the end of the conditional #ifndef XXXXX.H statement. Substitute theactual name of the header file for XXXXX in the preceding example to make itapplicable for your programs.
54. Difference between arrays andpointers?
- Pointersare used to manipulate data using the address. Pointers use* operator to access the datapointed to by them.
- Arrays use subscripted variables to access and manipulate data.Array variables can be equivalently written using pointerexpression.
55. What are the advantages of thefunctions?
- Debuggingis easier
- It is easier to understand the logic involved in theprogram.
- Testing is easier.
- Recursive call is possible.
- Irrelevant details in the user point of view are hidden infunctions.
- Functions are helpful in generalizing the program.
56. Is NULL always defined as 0?
NULL is defined as either 0 or (void*)0. These values are almost identical; either a literalzero or a void pointer is converted automatically to any kind ofpointer, as necessary, whenever a pointer is needed (although thecompiler can't always tell when a pointer is needed).
57. What is the difference betweenNULL and NUL?
NULL is a macro defined in for the nullpointer.
NUL is the name of the first character in the ASCIIcharacter set. It corresponds to a zero value. There's no standardmacro NUL in C, but some people like to define it.
The digit '0' corresponds to avalue of 48, decimal. Don't confuse the digit '0' with the value of '' (NUL)! NULL can be defined as (void*) 0, NUL as ''.
58. Can the sizeof operator be used to tell the sizeof an array passed to a function?
No. There'sno way to tell, at runtime, how many elements are in an arrayparameter just by looking at the array parameter itself. Remember,passing an array to a function is exactly the same as passing apointer to the first element.
59. Is using exit() the same as using return?
No. Theexit() function is used toexit your program and return control to the operating system. Thereturn statement is used toreturn from a function and return control to the calling function.If you issue a return from themain() function, you areessentially returning control to the calling function, which is theoperating system. In this case, the return statement and exit() function aresimilar.
60. Can math operations be performed ona void pointer?
No. Pointeraddition and subtraction are based on advancing the pointer by anumber of elements. By definition, if you have a void pointer, youdon't know what it's pointing to, so you don't know the size ofwhat it's pointing to. If you want pointer arithmetic to work onraw addresses, use character pointers.
61. Can the size of an array bedeclared at runtime?
No. In anarray declaration, the size must be known at compile time. Youcan't specify a size that's known only at runtime. For example, ifj is a variable, you can'twrite code like this:
char array[j];
Some languages provide this latitude. C doesn't. If it did, thestack would be more complicated, function calls would be moreexpensive, and programs would run a lot slower. If you know thatyou have an array but you won't know until runtime how big it willbe, declare a pointer to it and use malloc() or calloc() to allocate the array from theheap.
62. Can you add pointerstogether?
No, you can'tadd pointers together. If you live at 1332 Lakeview Drive, and yourneighbor lives at 1364 Lakeview, what's 1332+1364? It's a number,but it doesn't mean anything. If you try to perform this type ofcalculation with pointers in a C program, your compiler willcomplain.
The only time the addition of pointers might come up is if you tryto add a pointer and the difference of two pointers.
63. Are pointers integers?
No, pointersare not integers. A pointer is an address. It is merely a positivenumber and not an integer.
64.How do you redirect a standardstream?
Mostoperating systems, including DOS, provide a means to redirectprogram input and output to and from different devices. This meansthat rather than your program output (stdout) going to thescreen; it can be redirected to a file or printer port. Similarly,your program's input (stdin) can come from a file ratherthan the keyboard. In DOS, this task is accomplished using theredirection characters, <</B> and >. Forexample, if you wanted a program named PRINTIT.EXE toreceive its input (stdin) from a file namedSTRINGS.TXT, you would enter the following command at theDOS prompt:
C:> PRINTIT
Notice that the name of the executable file always comes first. Theless-than sign (<</B>) tells DOS to take the stringscontained in STRINGS.TXT and use them as input for thePRINTIT program.
The following example would redirect the program's output to thePRN device, usually the printer attached onLPT1:
C:> REDIR > PRN
Alternatively, you might want to redirect the program's output to afile, as the following example shows:
C:> REDIR > REDIR.OUT
In this example, all output that would have normally appearedon-screen will be written to the file REDIR.OUT.
Redirection of standard streams does not always have to occur atthe operating system. You can redirect a standard stream fromwithin your program by using the standard C library function namedfreopen(). For example, if youwanted to redirect the stdout standard stream within yourprogram to a file named OUTPUT.TXT, you would implement thefreopen() function as shownhere:
... freopen(output.txt, w, stdout);...
Now, every output statement (with printf(), puts(), putch(), and so on) in your program willappear in the file OUTPUT.TXT.
65. What is a method?
Method is away of doing something, especially a systematic way; implies anorderly logical arrangement (usually in steps).
66. What is the easiest searchingmethod to use?
Just asqsort() was the easiestsorting method, because it is part of the standard library,bsearch() is the easiestsearching method to use. If the given array is in the sorted order,bsearch() is the bestmethod.
Following is the prototype for bsearch():
void* bsearch(const void *key, const void*buf, size_t num, size_t size, int (*comp)(const void*, constvoid*));
Another simple searching method is a linear search. A linear searchis not as fast as bsearch()for searching among a large number of items, but it is adequate formany purposes. A linear search might be the only method available,if the data isn't sorted or can't be accessed randomly. A linearsearch starts at the beginning and sequentially compares the key toeach element in the data set.
67. Is it better to use a pointer tonavigate an array of values, or is it better to use a subscriptedarray name?
It's easierfor a C compiler to generate good code for pointers than forsubscripts.
68. What is indirection?
If youdeclare a variable, its name is a direct reference to its value. Ifyou have a pointer to a variable, or any other object in memory,you have an indirect reference to its value.
69. How are portions of a programdisabled in demo versions?
If you aredistributing a demo version of your program, the preprocessor canbe used to enable or disable portions of your program. Thefollowing 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 ofthis program!n");
return(0);
#endif
...
}
70. What is modularprogramming?
If a programis large, it is subdivided into a number of smaller programs thatare called modules or subprograms. If a complex problem is solvedusing more modules, this approach is known as modularprogramming.
71. How can you determine the maximumvalue that a numeric variable can hold?
For integraltypes, on a machine that uses two's complement arithmetic (which isjust about any machine you're likely to use), a signed type canhold 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 ofbits) - 1. For instance, a 16-bit signed integer can hold numbersfrom -2^^15 (= -32768) to +2^^15 - 1 (= 32767).
72. How reliable are floating-pointcomparisons?
Floating-point numbers are the black art of computerprogramming. One reason why this is so is that there is no optimalway to represent an arbitrary number. The Institute of Electricaland Electronic Engineers (IEEE) has developed a standard for therepresentation of floating-point numbers, but you cannot guaranteethat every machine you use will conform to the standard.
Even if your machine does conform to the standard, there are deeperissues. It can be shown mathematically that there are an infinitenumber of real numbers between any two numbers. For the computer todistinguish between two numbers, the bits that represent them mustdiffer. To represent an infinite number of different bit patternswould take an infinite number of bits. Because the computer mustrepresent a large range of numbers in a small number of bits(usually 32 to 64 bits), it has to make approximate representationsof most numbers.
Because floating-point numbers are so tricky to deal with, it'sgenerally bad practice to compare a floating-point number forequality with anything. Inequalities are much safer.
73. Which expression always returntrue? Which always return false?
Expressionif(a=0) always returnfalse.
Expression if(a=1) alwaysreturn true.
74. How many levels deep can includefiles be nested?
Even thoughthere is no limit to the number of levels of nested include filesyou can have, your compiler might run out of stack space whiletrying to include an inordinately high number of files. This numbervaries according to your hardware configuration and possibly yourcompiler.
75. What is the difference betweendeclaring a variable and defining a variable?
Declaring avariable means describing its type to the compiler but notallocating any space for it. Defining a variable means declaring itand also allocating space to hold the variable. You can alsoinitialize a variable at the time it is defined.
76. How can I make sure that my programis the only one accessing a file?
By using thesopen() function, you can opena file in shared mode and explicitly deny reading and writingpermissions to any other program but yours. This task isaccomplished by using the SH_DENYWR shared flag to denote that yourprogram is going to deny any writing or reading attempts by otherprograms.
For example, the following snippet of code shows a file beingopened in shared mode, denying access to all other files:
fileHandle = sopen("C:DATASETUP.DAT", O_RDWR,SH_DENYWR);
By issuing this statement, all other programs are denied access tothe SETUP.DAT file. If another program were to try to openSETUP.DAT for reading or writing, it would receive anEACCES error code, denotingthat access is denied to the file.
77. How can I sort a linkedlist?
Both themerge sort and the radix sort are good sorting algorithms to usefor linked lists.
78. Is it better to use malloc() or calloc()?
Both themalloc() and the calloc() functions are used to allocatedynamic memory. Each operates slightly different from the other.malloc() takes a size andreturns a pointer to a chunk of memory at least that big:
void* malloc(size_tsize);
calloc() takes a number ofelements, and the size of each, and returns a pointer to a chunk ofmemory at least big enough to hold them all:
void* calloc( size_t numElements, size_tsizeOfElement);
There's one major difference and one minor difference between thetwo functions. The major difference is that malloc() doesn't initialize the allocatedmemory. The first time malloc() gives you a particular chunk ofmemory, the memory might be full of zeros. If memory has beenallocated, freed, and reallocated, it probably has whatever junkwas left in it. That means, unfortunately, that a program might runin simple cases (when memory is never reallocated) but break whenused harder (and when memory is reused). calloc() fills the allocated memory withall zero bits. That means that anything there you're going to useas 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. Anythingyou're going to use as a floator double is set to all zerobits; that's a floating-point zero on some types of machines, butnot on all.
The minor difference between the two is that calloc() returns an array of objects;malloc() returns one object.Some people use calloc() tomake clear that they want an array.
79. What does it mean when a pointer isused in an ifstatement?
Any time apointer is used as a condition, it means "Is this a non-nullpointer?" A pointer can be used in an if, while, for, or do/while statement, or in a conditionalexpression.
80. Array is an lvalue ornot?
An lvalue wasdefined as an expression to which a value can be assigned. Is anarray an expression to which we can assign a value? The answer tothis question is no, because an array is composed of severalseparate array elements that cannot be treated as a whole forassignment purposes.
The following statement is therefore illegal:
int x[5], y[5];
x = y;
Additionally, you might want to copy the whole array all at once.You can do so using a library function such as the memcpy() function, which is shownhere:
memcpy(x, y, sizeof(y));
It should be noted here that unlike arrays, structures can betreated as lvalues. Thus, you can assign one structure variable toanother structure variable of the same type, such as this:
typedef struct t_name {
char last_name[25];
char first_name[15];
char middle_init[2];
} NAME;
...
NAME my_name, your_name;
...
your_name = my_name;
81. What is an lvalue?
An lvalue isan expression to which a value can be assigned. The lvalueexpression is located on the left side of an assignment statement,whereas an rvalue is located on the right side of an assignmentstatement. Each assignment statement must have an lvalue and anrvalue. The lvalue expression must reference a storable variable inmemory. It cannot be a constant.
82. Diffenentiate between an internalstatic and external static variable?
An internalstatic variable is declared inside a block with static storage class whereas an externalstatic variable is declared outside all the blocks in a file. Aninternal static variable has persistent storage, block scope and nolinkage. An external static variable has permanent storage, filescope and internal linkage.
83. What is the difference between astring and an array?
An array isan array of anything. A string is a specific kind of an array witha well-known convention to determine its length.
There are two kinds of programming languages: those in which astring is just an array of characters, and those in which it's aspecial type. In C, a string is just an array of characters (typechar), with one wrinkle: a C string always ends with a NULcharacter. The "value" of an array is the same as the address of(or a pointer to) the first element; so, frequently, a C string anda pointer to char are used tomean the same thing.
An array can be any length. If it's passed to a function, there'sno way the function can tell how long the array is supposed to be,unless some convention is used. The convention for strings isNUL termination; the last character is an ASCII NUL('') character.
84. What is an argument? What is thedifference between formal arguments and actualarguments?
An argumentis an entity used to pass the data from calling funtion to thecalled funtion. Formal arguments are the arguments available in thefuntion definition. They are preceded by their own data types.Actual arguments are available in the function call.
85. What are advantages anddisadvantages of external storage class?
Advantages ofexternal storage class
1) Persistent storage of a variable retains the latest value
2) The value is globally available
Disadvantages of external storage class
1) The storage for an external variable exists even when thevariable is not needed
2) The side effect may produce surprising output
3) Modification of the program is difficult
4) Generality of a program is affected
86. What is a voidpointer?
A voidpointer is a C convention for a raw address. The compiler has noidea what type of object a void pointer really points to. If youwrite
int *ip;
ip points to an int. If you write
void *p;
p doesn't point to avoid!
In C and C++, any time you need a void pointer, you can use anotherpointer type. For example, if you have a char*, you can pass it to a function thatexpects a void*. You don'teven need to cast it. In C (but not in C++), you can use avoid* any time you need anykind of pointer, without casting. (In C++, you need to castit).
A void pointer is used for working with raw memory or for passing apointer to an unspecified type.
Some C code operates on raw memory. When C was first invented,character pointers (char*)were used for that. Then people started getting confused about whena character pointer was a string, when it was a character array,and when it was raw memory.
87. How can type-insensitive macros becreated?
A type-insensitivemacro is a macro that performs the same basic operation ondifferent data types.
This task can be accomplished by using the concatenation operatorto create a call to a type-sensitive function based on theparameter passed to the macro. The following program provides anexample:
#define SORT(data_type) sort_##data_type
void sort_int(int** i);
void sort_long(long** l);
void sort_float(float** f);
void sort_string(char** s);
void main(void) {
int** ip;
long** lp;
float** fp;
char** cp;
...
SORT(int)(ip);
SORT(long)(lp);
SORT(float)(fp);
SORT(char)(cp);
...
}
This program contains four functions to sort four different datatypes: int, long, float, and string (notice that only thefunction prototypes are included for brevity). A macro namedSORT was created to take thedata type passed to the macro and combine it with the sort_ string to form a valid function callthat is appropriate for the data type being sorted. Thus, thestring
sort(int)(ip);
translates into
sort_int(ip);
after being run through the preprocessor.
88. When should a type cast not beused?
A type castshould not be used to override a const or volatile declaration. Overriding thesetype modifiers can cause the program to fail to runcorrectly.
A type cast should not be used to turn a pointer to one type ofstructure or data type into another. In the rare events, in whichthis action is beneficial, using a union to hold the values makes theprogrammer's intentions clearer.
89. When is a switch statement better than multipleif statements?
Aswitch statement is generallybest to use when you have more than two conditional expressionsbased on a single variable of numeric type.
90. What is storage class and what arestorage variable?
A storageclass is an attribute that changes the behavior of a variable. Itcontrols the lifetime, scope and linkage.
There are five types of storage classes
1) auto
2) static
3) extern
4) register
5) typedef
91. What is a staticfunction?
A staticfunction is a function whose scope is limited to the current sourcefile. Scope refers to the visibility of a function or variable. Ifthe function or variable is visible outside of the current sourcefile, it is said to have global, or external, scope. If thefunction or variable is not visible outside of the current sourcefile, it is said to have local, or static, scope.
92. How can I sort things that are toolarge to bring into memory?
A sortingprogram that sorts items that are on secondary storage (disk ortape) rather than primary storage (memory) is called an externalsort. Exactly how to sort large data depends on what is meant bytoo large to fit in memory. If the items to be sorted arethemselves too large to fit in memory (such as images), but therearen't many items, you can keep in memory only the sort key and avalue indicating the data's location on disk. After the key/valuepairs are sorted, the data is rearranged on disk into the correctorder. If too large to fit in memory means that there are too manyitems to fit into memory at one time, the data can be sorted ingroups that will fit into memory, and then the resulting files canbe merged. A sort such as a radix sort can also be used as anexternal sort, by making each bucket in the sort a file. Even thequick sort can be an external sort. The data can be partitioned bywriting it to two smaller files. When the partitions are smallenough to fit, they are sorted in memory and concatenated to formthe sorted file.
93. What is a pointervariable?
A pointervariable is a variable that may contain the address of anothervariable or any valid address in the memory.
94. What is a pointer value andaddress?
A pointervalue is a data object that refers to a memory location. Eachmemory locaion is numbered in the memory. The number attached to amemory location is called the address of the location.
95. What is a modulus operator? Whatare the restrictions of a modulus operator?
A modulus operator gives the remainder value. Theresult of x%y is obtained byx - (x/y)*y. This operator isapplied only to integral operands and cannot be applied to float ordouble.
96. What is a macro, and how do youuse it?
A macro is apreprocessor directive that provides a mechanism for tokenreplacement in your source code. Macros are created by using the#define statement.
Here is an example of a macro: macros can also utilize specialoperators such as the stringizing operator (#) and the concatenation operator(##).The stringizing operatorcan be used to convert macro parameters to quoted strings, as inthe following example:
#define DEBUG_VALUE(v) printf("#v isequal to %dn", v)
In your program, you can check the value of a variable by invokingthe DEBUG_VALUE macro:
...
int x = 20;
DEBUG_VALUE(x);
...
The preceding code prints x,which is equal to 20, on-screen. This example shows that thestringizing operator used with macros can be a very handy debuggingtool.
97. Differentiate between a linker andlinkage?
A linkerconverts an object code into an executable code by linking togetherthe necessary build in functions. The form and place of declarationwhere the variable is declared in a program determine the linkageof variable.
98. What is a function and built-infunction?
A largeprogram is subdivided into a number of smaller programs orsubprograms. Each subprogram specifies one or more actions to beperformed for a large program. Such subprograms arefunctions.
The function supports only static and extern storage classes. Bydefault, function assumes extern storage class. Functions haveglobal scope. Only register or auto storage class is allowed in thefunction parameters. Built-in functions that predefined andsupplied along with the compiler are known as built-in functions.They are also known as library functions.
99. What is the difference between gotoand longjmp() and setjmp()?
Agoto statement implements alocal jump of program execution, and the longjmp() and setjmp() functions implement a nonlocal,or far, jump of program execution.
Generally, a jump in execution of any kind should be avoidedbecause it is not considered good programming practice to use suchstatements as goto andlongjmp in your program.
A goto statement simplybypasses code in your program and jumps to a predefined position.To use the goto statement, yougive it a labeled position to jump to. This predefined positionmust be within the same function. You cannot implement gotosbetween functions.
When your program calls setjmp(), the current state of yourprogram is saved in a structure of type jmp_buf. Later, your program can call thelongjmp() function to restorethe program's state as it was when you called setjmp(). Unlike the goto statement, the longjmp() and setjmp() functions do not need to beimplemented in the same function.
However, there is a major drawback to using these functions: yourprogram, when restored to its previously saved state, will lose itsreferences to any dynamically allocated memory between thelongjmp() and the setjmp(). This means you will waste memoryfor every malloc() orcalloc() you have implementedbetween your longjmp() andsetjmp(), and your programwill be horribly inefficient. It is highly recommended that youavoid using functions such as longjmp() and setjmp() because they, like thegoto statement, are quiteoften an indication of poor programming practice.
100. Is it acceptable to declare/definea variable in a C header?
A globalvariable that must be accessed from more than one file can andshould be declared in a header file. In addition, such a variablemust be defined in one source file.
Variables should not be defined in header files, because the headerfile can be included in multiple source files, which would causemultiple definitions of the variable. The ANSI C standard willallow multiple external definitions, provided that there is onlyone initialization. But because there's really no advantage tousing this feature, it's probably best to avoid it and maintain ahigher level of portability.
Global variables that do not have to be accessed from more than onefile should be declared static and should not appear in a headerfile.
101. Why should I prototype afunction?
A functionprototype tells the compiler what kind of arguments a function islooking to receive and what kind of return value a function isgoing to give back. This approach helps the compiler ensure thatcalls to a function are made correctly and that no erroneous typeconversions are taking place.
102. What is the quickest searchingmethod to use?
A binarysearch, such as bsearch()performs, is much faster than a linear search. A hashing algorithmcan provide even faster searching. One particularly interesting andfast method for searching is to keep the data in a digital trie. Adigital trie offers the prospect of being able to search for anitem in essentially a constant amount of time, independent of howmany items are in the data set.
A digital trie combines aspects of binary searching, radixsearching, and hashing. The term digital trie refers to the datastructure used to hold the items to be searched. It is a multileveldata structure that branches N ways at each level.
103. What are the advantages of autovariables?
1) The sameauto variable name can be used in different blocks.
2) There is no side effect by changing the values in theblocks.
3) The memory is economically used.
4) Auto variables have inherent protection because of localscope.
104. What are the characteristics ofarrays in C?
1) An arrayholds elements that have the same data type.
2) Array elements are stored in subsequent memory locations.
3) Two-dimentional array elements are stored row by row insubsequent memory locations.
4) Array name represents the address of the starting element.
5) Array size should be mentioned in the declaration. Array sizemust be a constant expression and not a variable.
105. How do you print only part of astring?
printf("First 11 characters: .11sn",source_str);
资料来自:http://www.cnitblog.com/chlclan/archive/2006/06/22/12668.html
更多阅读
转载 C语言:随机函数rand()、srand()、random()和rando
原文地址:C语言:随机函数rand()、srand()、random()和randomized()的区别和用法作者:猎空声明一点:在VC++中,没有random()和randomize()函数,只有rand()和srand()函数。其中,random()和randomize()函数的使用的方法分别与rand()和srand()
使用Visual C++6.0编写简单C语言程序入门教程 visual c 编写c语言
使用Visual C++6.0编写简单C语言程序入门教程——简介本教程适用于C语言初学者,使用VC++6.0编写简单的程序。Visual C++6.0作为学习C语言的编程工具在合适不过了,工具比较简洁,容易上手。下面我将一步步带领大家一步步操作,教会大家如何
如何学习C语言编程
如何学习C语言编程——简介6 部分:准备工作 变量的使用 使用条件语句 学习循环语句 使用函数 不断学习诞生于上世纪70年代的C语言是一门古老的语言了, 但作为一门底层语言,时至今日它仍然非常强大。学习C语言能够为学习其他更复杂
转载 C语言贪心算法 c语言贪心算法
你真牛原文地址:C语言贪心算法作者:人鱼的泪贪心算法开放分类:算法、信息学贪心算法所谓贪心算法是指,在对问题求解时,总是做出在当前看来是最好的选择。也就是说,不从整体最优上加以考虑,他所做出的仅是在某种意义上的局部最
读《小飞侠彼得潘》有感(宋嘉铭) 小飞侠彼得潘读后感
读《小飞侠彼得潘》有感五(2)班宋嘉铭《小飞侠》彼得潘讲述了一个叫彼得潘的小男孩是印第安人部落的队长,他们生活在永无乡,那是一个永远长不大的地方。他们在这里自由自在,一点也不拘束,可有一点美中不足,那就是他们没有妈妈。于是