Showing posts with label C language latest technical interview questions and answers. Show all posts
Showing posts with label C language latest technical interview questions and answers. Show all posts

Sunday, April 6, 2008

C Language Latest Technical Interview Questions & Answers for Placement Papers, Project Notes and Solved Tutorials


C Language Technical Interview Questions - 16
C Language Floating Point Questions - 15
C language Library Functions Questions - 14
C language technical interview questions - 13
ANSI C technical interview questions and Notes -12
C language latest notes and Technical Interview Questions 11
C language Technical Interview Questions and Project Notes / Topics - 10
C language Questions and answers - 9
C language arrays pointers questions - 8
C language technical interview questions - 7
C language pointers questions - 6
C language Technical Interview 2008 questions 5
C language technical interview questions with answers and solved programs 4
C language Important Technical Interview Questions...
Embedded Systems Interview Questions
C language Technical Interview Questions for 2008

See more technical interview questions of various computer languages of recent and previous years for various reputed IT Companies in India and abroad. keep watching PreviousPapers.blogspot.com to see and download more free stuff.

Saturday, April 5, 2008

C Language Technical Interview Questions - 16

Declarations and Initializations:

1. How do you decide which integer type to use?

A: If you might need large values (above 32,767 or below -32,767), use long. Otherwise, if space is very important (i.e. if there are large arrays or many structures), use short. Otherwise, use int. If well-defined overflow characteristics are important and negative values are not, or if you want to steer clear of sign- extension problems when manipulating bits or bytes, use one of the corresponding unsigned types. (Beware when mixing signed and unsigned values in expressions, though.) Although character types (especially unsigned char) can be used as "tiny" integers, doing so is sometimes more trouble than it's worth, due to unpredictable sign extension and increased code size.

A similar space/time tradeoff applies when deciding between float and double. None of the above rules apply if the address of a variable is taken and must have a particular type. If for some reason you need to declare something with an *exact* size (usually the only good reason for doing so is when attempting to conform to some externally-imposed storage layout, but see question 20.5), be sure to encapsulate the choice behind an appropriate typedef.

2. What should the 64-bit type on a machine that can support it?

A: The forthcoming revision to the C Standard (C9X) specifies type long long as effectively being at least 64 bits, and this type has been implemented by a number of compilers for some time. (Others have implemented extensions such as __longlong.) On the other hand, there's no theoretical reason why a compiler couldn't implement type short int as 16, int as 32, and long int as 64 bits, and some compilers do indeed choose this arrangement.

3. What's the best way to declare and define global variables and functions?

A: First, though there can be many "declarations" (and in many translation units) of a single "global" (strictly speaking, "external") variable or function, there must be exactly one "definition". (The definition is the declaration that actually allocates space, and provides an initialization value, if any.) The best arrangement is to place each definition in some relevant .c file, with an external declaration in a header (".h") file, which is #included wherever the declaration is needed. The .c file containing the definition should also #include the same header file, so that the compiler can check that the definition matches the declarations. This rule promotes a high degree of portability: it is consistent with the requirements of the ANSI C Standard, and is also consistent with most pre-ANSI compilers and linkers. (Unix compilers and linkers typically use a "common model" which allows multiple definitions, as long as at most one is initialized; this behavior is mentioned as a "common extension" by the ANSI Standard, no pun intended. A few very odd systems may require an explicit initializer to distinguish a definition from an external declaration.) It is possible to use preprocessor tricks to arrange that a line like DEFINE(int, i); need only be entered once in one header file, and turned into a definition or a declaration depending on the setting of some macro, but it's not clear if this is worth the trouble. It's especially important to put global declarations in header files if you want the compiler to catch inconsistent declarations for you. In particular, never place a prototype for an external function in a .c file: it wouldn't generally be checked for consistency with the definition, and an incompatible prototype is worse than useless.

4: What does extern mean in a function declaration?

A: It can be used as a stylistic hint to indicate that the function's definition is probably in another source file, but there is no formal difference between extern int f(); and int f();

5: What's the auto keyword good for?

A: Nothing; it's archaic.

6. Define a linked list and tried typedef struct { char *item; NODEPTR next; } *NODEPTR; but the compiler give to error messages. Can't a structure in C contain a pointer to itself?

A: Structures in C can certainly contain pointers to themselves; the discussion and example in section 6.5 of K&R make this clear. The problem with the NODEPTR example is that the typedef has not been defined at the point where the "next" field is declared. To fix this code, first give the structure a tag ("struct node"). Then, declare the "next" field as a simple "struct node *", or disentangle the typedef declaration from the structure definition, or both. One corrected version would be struct node { char *item; struct node *next; }; typedef struct node *NODEPTR; and there are at least three other equivalently correct ways of arranging it. A similar problem, with a similar solution, can arise when attempting to declare a pair of typedef'ed mutually referential structures.

7: How do you declare an array of N pointers to functions returning pointers to functions returning pointers to characters?

A: The first part of this question can be answered in at least three ways:

1. char *(*(*a[N])())(); 2. Build the declaration up incrementally, using typedefs: typedef char *pc; /* pointer to char */ typedef pc fpc(); /* function returning pointer to char */ typedef fpc *pfpc; /* pointer to above */ typedef pfpc fpfpc(); /* function returning... */ typedef fpfpc *pfpfpc; /* pointer to... */ pfpfpc a[N]; /* array of... */ 3. Use the cdecl program, which turns English into C and vice versa: cdecl> declare a as array of pointer to function returning pointer to function returning pointer to char char *(*(*a[])())() cdecl can also explain complicated declarations, help with casts, and indicate which set of parentheses the arguments go in (for complicated function definitions, like the one above). Any good book on C should explain how to read these complicated C declarations "inside out" to understand them ("declaration mimics use"). The pointer-to-function declarations in the examples above have not included parameter type information. When the parameters have complicated types, declarations can *really* get messy.

8: How you declare a function that can return a pointer to a function of the same type? you will building a state machine with one function for each state, each of which returns a pointer to the function for the next state. But you can't find a way to declare the functions.

A: We can't quite do it directly. Either have the function return a generic function pointer, with some judicious casts to adjust the types as the pointers are passed around; or have it return a structure containing only a pointer to a function returning that structure.

9. Some compiler is complaining about an invalid redeclaration of a function, but you only define it once and call it once.

A: Functions which are called without a declaration in scope (perhaps because the first call precedes the function's definition) are assumed to be declared as returning int (and without any argument type information), leading to discrepancies if the function is later declared or defined otherwise. Non-int functions must be declared before they are called. Another possible source of this problem is that the function has the same name as another one declared in some header file.

10. What's the right declaration for main()? Is void main() correct?

A: But no, it's not correct

11. What are you allowed to assume about the initial values of variables which are not explicitly initialized? If global variables start out as "zero", is that good enough for null pointers and floating-point zeroes?

A: Uninitialized variables with "static" duration (that is, those declared outside of functions, and those declared with the storage class static), are guaranteed to start out as zero, as if the programmer had typed "= 0". Therefore, such variables are implicitly initialized to the null pointer (of the correct type; see also section 5) if they are pointers, and to 0.0 if they are floating-point. Variables with "automatic" duration (i.e. local variables without the static storage class) start out containing garbage, unless they are explicitly initialized. (Nothing useful can be predicted about the garbage.) Dynamically-allocated memory obtained with malloc() and realloc() is also likely to contain garbage, and must be initialized by the calling program, as appropriate. Memory obtained with calloc() is all-bits-0, but this is not necessarily useful for pointer or floating-point values

12. This code, straight out of a book, isn't compiling:

int f() { char a[] = "Hello, world!"; }

A: Perhaps you have a pre-ANSI compiler, which doesn't allow initialization of "automatic aggregates" (i.e. non-static local arrays, structures, and unions). (As a workaround, and depending on how the variable a is used, you may be able to make it global or static, or replace it with a pointer, or initialize it by hand with strcpy() when f() is called.)

13. What's wrong with this initialization? char *p = malloc(10); your compiler is complaining about an "invalid initializer", or something.

A: Is the declaration of a static or non-local variable? Function calls are allowed only in initializers for automatic variables (that is, for local, non-static variables).

14. What is the difference between these initializations? char a[] = "string literal"; char *p = "string literal"; My program crashes if I try to assign a new value to p[i].

A: A string literal can be used in two slightly different ways. As an array initializer (as in the declaration of char a[]), it specifies the initial values of the characters in that array. Anywhere else, it turns into an unnamed, static array of characters, which may be stored in read-only memory, which is why you can't safely modify it. In an expression context, the array is converted at once to a pointer, as usual (see section 6), so the second declaration initializes p to point to the unnamed array's first element. (For compiling old code, some compilers have a switch controlling whether strings are writable or not.)

15. I finally figured out the syntax for declaring pointers to functions, but now how do I initialize one?

A: Use something like extern int func(); int (*fp)() = func; When the name of a function appears in an expression like this, it "decays" into a pointer (that is, it has its address implicitly taken), much as an array name does. An explicit declaration for the function is normally needed, since implicit external function declaration does not happen in this case (because the function name in the initialization is not part of a function call).

C Language Floating Point Questions - 15

Floating Point

1. When I set a float variable to, say, 3.1, why is printf printing it as 3.0999999?
A: Most computers use base 2 for floating-point numbers as well as for integers. In base 2, one divided by ten is an infinitely- repeating fraction (0.0001100110011...), so fractions such as 3.1 (which look like they can be exactly represented in decimal) cannot be represented exactly in binary. Depending on how carefully your compiler's binary/decimal conversion routines (such as those used by printf) have been written, you may see discrepancies when numbers (especially low-precision floats) not exactly representable in base 2 are assigned or read in and then printed (i.e. converted from base 10 to base 2 and back again).

2. I'm trying to take some square roots, but I'm getting crazy numbers.Why ?
A: Make sure that you have #included , and correctly declared other functions returning double. (Another library function to be careful with is atof(), which is declared in )

3. I'm trying to do some simple trig, and I am #including , but I keep getting "undefined: sin" compilation errors.
A: Make sure you're actually linking with the math library. For instance, under Unix, you usually need to use the -lm option, at the *end* of the command line, when compiling/linking. 14.4: My floating-point calculations are acting strangely and giving me different answers on different machines.

If the problem isn't that simple, recall that digital computers usually use floating-point formats which provide a close but by no means exact simulation of real number arithmetic. Underflow, cumulative precision loss, and other anomalies are often troublesome.

Don't assume that floating-point results will be exact, and especially don't assume that floating-point values can be compared for equality. (Don't throw haphazard "fuzz factors" in, either; )

These problems are no worse for C than they are for any other computer language. Certain aspects of floating-point are usually defined as "however the processor does them" , otherwise a compiler for a machine without the "right" model would have to do prohibitively expensive emulations.

This article cannot begin to list the pitfalls associated with, and workarounds appropriate for, floating-point work. A good numerical programming text should cover the basics;

4. What's a good way to check for "close enough" floating-point equality?
A: Since the absolute accuracy of floating point values varies, by definition, with their magnitude, the best way of comparing two floating point values is to use an accuracy threshold which is relative to the magnitude of the numbers being compared. Rather than

double a, b;
...
if(a == b) /* WRONG */
use something like
#include
if(fabs(a - b) <= epsilon * fabs(a)) for some suitably-chosen degree of closeness epsilon (as long as a is nonzero!).
5. How do I round numbers?
A: The simplest and most straightforward way is with code like
(int)(x + 0.5)
This technique won't work properly for negative numbers, though (for which you could use something like (int)(x <>6. Why doesn't C have an exponentiation operator?
A: Because few processors have an exponentiation instruction. C has a pow() function, declared in , although explicit multiplication is usually better for small positive integral exponents.

7. The predefined constant M_PI seems to be missing from my machine's copy of
A: That constant (which is apparently supposed to be the value of pi, accurate to the machine's precision), is not standard. If you need pi, you'll have to define it yourself, or compute it with 4*atan(1.0).

8. How do you test for IEEE NaN and other special values?
A: Many systems with high-quality IEEE floating-point implementations provide facilities (e.g. predefined constants, and functions like isnan(), either as nonstandard extensions in or perhaps in or ) to deal with these values cleanly, and work is being done to formally standardize such facilities. A crude but usually effective test for NaN is exemplified by
#define isnan(x) ((x) != (x))
although non-IEEE-aware compilers may optimize the test away.
C9X will provide isnan(), fpclassify(), and several other
classification routines.

Another possibility is to to format the value in question using sprintf(): on many systems it generates strings like "NaN" and "Inf" which you could compare for in a pinch.

9. What's a good way to implement complex numbers in C?
A: It is straightforward to define a simple structure and some arithmetic functions to manipulate them. C9X will support complex as a standard type.

Free download online recent and current year solved placement question papers 2008 of leading companies in India and Abroad. See More Latest and previous expert, common, basic, important, advanced questions asked in college admission, entrance tests and technical interviews for 2007, 2008 companies like Infosys, wipro, satyam computers, hcl, ibm, tcs, cisco, etc. Recent, latest reasoning, multiple choice questions, verbal, non verbal, mathematics questions with solutions / solved / answer keys, booklet. Group Discussion GD guide with topics for leading campus placement interview, placement drive, HR Interview Guide with Questions and answers, how to behave, Tips, preparation, most recently asked / important software testing interview, free tutorials for java, oracle, c, c++, networking, web designing, windows 2000, vista, etc. questions. Keep Watching Previouspapers.blogspot.com for more stuff!

C language Library Functions Questions - 14

C Language Library Functions

1. How can I convert numbers to strings (the opposite of atoi)? Is there an itoa() function?
A: Just use sprintf(). (Don't worry that sprintf() may be overkill, potentially wasting run time or code space; it works well in practice.)

You can obviously use sprintf() to convert long or floating- point numbers to strings as well (using %ld or %f).

2. Why does strncpy() not always place a '\0' terminator in the destination string?
A: strncpy() was first designed to handle a now-obsolete data structure, the fixed-length, not-necessarily-\0-terminated "string." (A related quirk of strncpy's is that it pads short strings with multiple \0's, out to the specified length.) strncpy() is admittedly a bit cumbersome to use in other
contexts, since you must often append a '\0' to the destination string by hand. You can get around the problem by using strncat() instead of strncpy(): if the destination string starts out empty, strncat() does what you probably wanted strncpy() to do. Another possibility is sprintf(dest, "%.*s", n, source) .

When arbitrary bytes (as opposed to strings) are being copied, memcpy() is usually a more appropriate function to use than strncpy().

3. Why do some versions of toupper() act strangely if given an upper-case letter? Why does some code call islower() before toupper()?
A: Older versions of toupper() and tolower() did not always work correctly on arguments which did not need converting (i.e. on digits or punctuation or letters already of the desired case). In ANSI/ISO Standard C, these functions are guaranteed to work appropriately on all character arguments.

4. How can I split up a string into whitespace-separated fields? How can I duplicate the process by which main() is handed argc and argv?
A: The only Standard function available for this kind of "tokenizing" is strtok(), although it can be tricky to use and it may not do everything you want it to. (For instance, it does not handle quoting.)

5. I need some code to do regular expression and wildcard matching.
A: Make sure you recognize the difference between classic regular expressions (variants of which are used in such Unix utilities as ed and grep), and filename wildcards (variants of which are used by most operating systems).

There are a number of packages available for matching regular expressions. Most packages use a pair of functions, one for "compiling" the regular expression, and one for "executing" it (i.e. matching strings against it). Look for header files named or , and functions called regcmp/regex, regcomp/regexec, or re_comp/re_exec. (These functions may exist in a separate regexp library.) A popular, freely- redistributable regexp package by Henry Spencer is available
from ftp.cs.toronto.edu in pub/regexp.shar.Z or in several other archives. The GNU project has a package called rx. Filename wildcard matching (sometimes called "globbing") is done in a variety of ways on different systems. On Unix, wildcards are automatically expanded by the shell before a process is invoked, so programs rarely have to worry about them explicitly.Under MS-DOS compilers, there is often a special object file which can be linked in to a program to expand wildcards while argv is being built. Several systems (including MS-DOS and VMS) provide system services for listing or opening files specified by wildcards. Check your compiler/library documentation.

6. I'm trying to sort an array of strings with qsort(), using strcmp() as the comparison function, but it's not working.
A: By "array of strings" you probably mean "array of pointers to char." The arguments to qsort's comparison function are pointers to the objects being sorted, in this case, pointers to pointers to char. strcmp(), however, accepts simple pointers to char. Therefore, strcmp() can't be used directly. Write an intermediate comparison function like this:
/* compare strings via pointers */
int pstrcmp(const void *p1, const void *p2)
{
return strcmp(*(char * const *)p1, *(char * const *)p2);
}

The comparison function's arguments are expressed as "generic pointers," const void *. They are converted back to what they "really are" (pointers to pointers to char) and dereferenced, yielding char *'s which can be passed to strcmp().

7. Now I'm trying to sort an array of structures with qsort(). My comparison function takes pointers to structures, but the compiler complains that the function is of the wrong type for qsort(). How can I cast the function pointer to shut off the warning?
A: The conversions must be in the comparison function, which must be declared as accepting "generic pointers" (const void *) as discussed in question 13.8 above. The comparison function might look like
int mystructcmp(const void *p1, const void *p2)
{
const struct mystruct *sp1 = p1;
const struct mystruct *sp2 = p2;
/* now compare sp1- ... */

(The conversions from generic pointers to struct mystruct pointers happen in the initializations sp1 = p1 and sp2 = p2; the compiler performs the conversions implicitly since p1 and p2 are void pointers.)

If, on the other hand, you're sorting pointers to structures, you'll need indirection,
sp1 = *(struct mystruct * const *)p1 .
In general, it is a bad idea to insert casts just to "shut the compiler up." Compiler warnings are usually trying to tell you something, and unless you really know what you're doing, you ignore or muzzle them at your peril.

8. How can I sort a linked list?
A: Sometimes it's easier to keep the list in order as you build it (or perhaps to use a tree instead). Algorithms like insertion sort and merge sort lend themselves ideally to use with linked lists. If you want to use a standard library function, you can allocate a temporary array of pointers, fill it in with pointers to all your list nodes, call qsort(), and finally rebuild the list pointers based on the sorted array.

9. How can I sort more data than will fit in memory?
A: You want an "external sort," which you can read about in Knuth, Volume 3. The basic idea is to sort the data in chunks (as much as will fit in memory at one time), write each sorted chunk to a
temporary file, and then merge the files. Your operating system may provide a general-purpose sort utility, and if so, you can try invoking it from within your program:

10. How can I get the current date or time of day in a C program?
A: Just use the time(), ctime(), localtime() and/or strftime() functions. Here is a simple example:
#include
#include
int main()
{
time_t now;
time(&now);
printf("It's %.24s.\n", ctime(&now));
return 0;
}

11. I know that the library function localtime() will convert a time_t into a broken-down struct tm, and that ctime() will convert a time_t to a printable string. How can I perform the inverse operations of converting a struct tm or a string into a time_t?
A: ANSI C specifies a library function, mktime(), which converts a struct tm to a time_t.
Converting a string to a time_t is harder, because of the wide variety of date and time formats which might be encountered. Some systems provide a strptime() function, which is basically the inverse of strftime(). Other popular functions are partime() (widely distributed with the RCS package) and getdate() (and a few others, from the C news distribution).

12. How can I add N days to a date? How can I find the difference between two dates?
A: The ANSI/ISO Standard C mktime() and difftime() functions provide some support for both problems. mktime() accepts non- normalized dates, so it is straightforward to take a filled-in
struct tm, add or subtract from the tm_mday field, and call mktime() to normalize the year, month, and day fields (and incidentally convert to a time_t value). difftime() computes the difference, in seconds, between two time_t values; mktime() can be used to compute time_t values for two dates to be subtracted.

These solutions are only guaranteed to work correctly for dates in the range which can be represented as time_t's. The tm_mday field is an int, so day offsets of more than 32,736 or so may
cause overflow. Note also that at daylight saving time changeovers, local days are not 24 hours long (so don't assume that division by 86400 will be exact).

13. Does C have any Year 2000 problems?
A: No, although poorly-written C programs do.

The tm_year field of struct tm holds the value of the year minus 1900; this field will therefore contain the value 100 for the year 2000. Code that uses tm_year correctly (by adding or subtracting 1900 when converting to or from human-readable 4-digit year representations) will have no problems at the turn of the millennium. Any code that uses tm_year incorrectly, however, such as by using it directly as a human-readable 2-digit year, or setting it from a 4-digit year with code like

tm.tm_year = yyyy % 100; /* WRONG */

or printing it as an allegedly human-readable 4-digit year with code like

printf("19%d", tm.tm_year); /* WRONG */
will have grave y2k problems indeed.

14. How to generate a random numbers ?
A: The Standard C library has one: rand(). The implementation on your system may not be perfect, but writing a better one isn't necessarily easy, either.

If you do find yourself needing to implement your own random number generator, there is plenty of literature out there; see the References. There are also any number of packages on the
net: look for r250, RANLIB, and FSULTRA Generators: Good Ones are Hard to Find".

15. How can I get random integers in a certain range?
A: The obvious way,
rand() % N /* POOR */
(which tries to return numbers from 0 to N-1) is poor, because the low-order bits of many random number generators are distressingly *non*-random. A better method is something like

(int)((double)rand() / ((double)RAND_MAX + 1) * N)

If you're worried about using floating point, you could use
rand() / (RAND_MAX / N + 1)

Both methods obviously require knowing RAND_MAX (which ANSI #defines in ), and assume that N is much less than
RAND_MAX.
(Note, by the way, that RAND_MAX is a *constant* telling you what the fixed range of the C library rand() function is. You cannot set RAND_MAX to some other value, and there is no way of requesting that rand() return numbers in some other range.)

If you're starting with a random number generator which returns floating-point values between 0 and 1, all you have to do to get integers from 0 to N-1 is multiply the output of that generator by N.

16. Each time I run my program, I get the same sequence of numbers back from rand(). Why?
A: You can call srand() to seed the pseudo-random number generator with a truly random initial value. Popular seed values are the time of day, or the elapsed time before the user presses a key
(although keypress times are hard to determine portably; (Note also that it's rarely useful to call srand() more than once during a run of a program; in particular, don't try calling srand() before each call to rand(), in an attempt to get "really random" numbers.)

17. I need a random true/false value, so I'm just taking rand() % 2, but it's alternating 0, 1, 0, 1, 0...
A: Poor pseudorandom number generators (such as the ones unfortunately supplied with some systems) are not very random in the low-order bits. Try using the higher-order bits:

18. How can I generate random numbers with a normal or Gaussian distribution?
A: Here is one method, recommended by Knuth and due originally to Marsaglia:
#include
#include

double gaussrand()
{
static double V1, V2, S;
static int phase = 0;
double X;

if(phase == 0) {
do {
double U1 = (double)rand() / RAND_MAX;
double U2 = (double)rand() / RAND_MAX;

V1 = 2 * U1 - 1;
V2 = 2 * U2 - 1;
S = V1 * V1 + V2 * V2;
} while(S <= 1 S == 0);

X = V1 * sqrt(-2 * log(S) / S);
} else
X = V2 * sqrt(-2 * log(S) / S);

phase = 1 - phase;

return X;
}

See the extended versions of this list for other ideas.

19. I keep getting errors due to library functions being undefined, but I'm #including all the right header files.
A: In general, a header file contains only declarations. In some cases (especially if the functions are nonstandard) obtaining the actual *definitions* may require explicitly asking for the correct libraries to be searched when you link the program. (#including the header doesn't do that.)

20. I'm still getting errors due to library functions being undefined, even though I'm explicitly requesting the right libraries while linking.
A: Many linkers make one pass over the list of object files and libraries you specify, and extract from libraries only those modules which satisfy references which have so far come up as undefined. Therefore, the order in which libraries are listed with respect to object files (and each other) is significant; usually, you want to search the libraries last. (For example, under Unix, put any -l options towards the end of the command line.)

21 What does it mean when the linker says that _end is undefined?
A: That message is a quirk of the old Unix linkers. You get an error about _end being undefined only when other symbols are undefined, too -- fix the others, and the error about _end will disappear.

C language technical interview questions - 13

C Technical Interview Question Set: Checking Program correct or not, find error program and technical interview questions
Stdio . h

1. What's wrong with this code?
char c;
while((c = getchar()) != EOF) ...
A: For one thing, the variable to hold getchar's return value must be an int. getchar() can return all possible character values, as well as EOF. By squeezing getchar's return value into a char, either a normal character might be misinterpreted as EOF, or the EOF might be altered (particularly if type char is unsigned) and so never seen.

2. Why does the code
while(!feof(infp)) {
fgets(buf, MAXLINE, infp);
fputs(buf, outfp);
}
copy the last line twice?
A: In C, end-of-file is only indicated *after* an input routine has tried to read, and failed. (In other words, C's I/O is not like Pascal's.) Usually, you should just check the return value of the input routine (in this case, fgets() will return NULL on end- of-file); often, you don't need to use feof() at all.

3. My program's prompts and intermediate output don't always show up on the screen, especially when I pipe the output through another program.
A: It's best to use an explicit fflush(stdout) whenever output should definitely be visible (and especially if the text does not end with \n). Several mechanisms attempt to perform the fflush() for you, at the "right time," but they tend to apply only when stdout is an interactive terminal.

4. How can I print a '%' character in a printf format string? I tried \%, but it didn't work.
A: Simply double the percent sign: %% .
\% can't work, because the backslash \ is the *compiler's* escape character, while here our problem is that the % is essentially printf's escape character.

5. Someone told me it was wrong to use %lf with printf(). How can printf() use %f for type double, if scanf() requires %lf?
A: It's true that printf's %f specifier works with both float and double arguments. Due to the "default argument promotions" (which apply in variable-length argument lists such as printf's, whether or not prototypes are in scope), values of type float are promoted to double, and printf() therefore sees only doubles. (printf() does accept %Lf, for long double.)

6. What printf format should I use for a typedef like size_t when I don't know whether it's long or some other type?
A: Use a cast to convert the value to a known, conservatively- sized type, then use the printf format matching that type. For example, to print the size of a type, you might use
printf("%lu", (unsigned long)sizeof(thetype));

7. How can I implement a variable field width with printf? That is, instead of %8d, I want the width to be specified at run time.
A: printf("%*d", width, x) will do just what you want.

8. How can I print numbers with commas separating the thousands? What about currency formatted numbers?
A: The functions in begin to provide some support for these operations, but there is no standard routine for doing either task. (The only thing printf() does in response to a custom locale setting is to change its decimal-point character.)

9. Why doesn't the call scanf("%d", i) work?
A: The arguments you pass to scanf() must always be pointers. To fix the fragment above, change it to scanf("%d", &i) .

10. Why doesn't this code:
double d;
scanf("%f", &d);
work?
A: Unlike printf(), scanf() uses %lf for values of type double, and %f for float.

11. How can I specify a variable width in a scanf() format string?
A: You can't; an asterisk in a scanf() format string means to suppress assignment. You may be able to use ANSI stringizing and string concatenation to accomplish about the same thing, or you can construct the scanf format string at run time.

12. When I read numbers from the keyboard with scanf "%d\n", it seems to hang until I type one extra line of input.
A: Perhaps surprisingly, \n in a scanf format string does *not* mean to expect a newline, but rather to read and discard characters as long as each is a whitespace character.

13. I'm reading a number with scanf %d and then a string with gets(), but the compiler seems to be skipping the call to gets()!
A: scanf %d won't consume a trailing newline. If the input number is immediately followed by a newline, that newline will immediately satisfy the gets().

As a general rule, you shouldn't try to interlace calls to scanf() with calls to gets() (or any other input routines); scanf's peculiar treatment of newlines almost always leads to trouble. Either use scanf() to read everything or nothing.

14.I figured I could use scanf() more safely if I checked its return value to make sure that the user typed the numeric values I expect, but sometimes it seems to go into an infinite loop.
A: When scanf() is attempting to convert numbers, any non-numeric characters it encounters terminate the conversion *and are left on the input stream*. Therefore, unless some other steps are
taken, unexpected non-numeric input "jams" scanf() again and again: scanf() never gets past the bad character(s) to encounter later, valid data. If the user types a character like `x' in response to a numeric scanf format such as %d or %f, code that simply re-prompts and retries the same scanf() call will immediately reencounter the same `x'.

15. Why does everyone say not to use scanf()? What should I use instead?
A: scanf() has a number of problems Also, its %s format has the same problem that gets() has -- it's hard to guarantee that the receiving buffer won't overflow.

More generally, scanf() is designed for relatively structured, formatted input (its name is in fact derived from "scan formatted"). If you pay attention, it will tell you whether it succeeded or failed, but it can tell you only approximately where it failed, and not at all how or why. It's nearly impossible to do decent error recovery with scanf(); usually it's far easier to read entire lines (with fgets() or the like), then interpret them, either using sscanf() or some other techniques. (Functions like strtol(), strtok(), and atoi() are often useful; If you do use any scanf variant, be sure to check the return value to make sure that the expected number of items were found. Also, if you use %s, be sure to guard against buffer overflow.

16. How can I tell how much destination buffer space I'll need for an arbitrary sprintf call? How can I avoid overflowing the destination buffer with sprintf()?
A: When the format string being used with sprintf() is known and relatively simple, you can sometimes predict a buffer size in an ad-hoc way. If the format consists of one or two %s's, you can
count the fixed characters in the format string yourself (or let sizeof count them for you) and add in the result of calling strlen() on the string(s) to be inserted. For integers, the number of characters produced by %d is no more than
((sizeof(int) * CHAR_BIT + 2) / 3 + 1) /* +1 for '-' */
(CHAR_BIT is in <limits.h>), though this computation may be over- conservative. (It computes the number of characters required for a base-8 representation of a number; a base-10 expansion is
guaranteed to take as much room or less.)

When the format string is more complicated, or is not even known until run time, predicting the buffer size becomes as difficult as reimplementing sprintf(), and correspondingly error-prone
(and inadvisable). A last-ditch technique which is sometimes suggested is to use fprintf() to print the same text to a bit bucket or temporary file, and then to look at fprintf's return value or the size of the file and worry about write errors).

If there's any chance that the buffer might not be big enough, you won't want to call sprintf() without some guarantee that the buffer will not overflow and overwrite some other part of memory. If the format string is known, you can limit %s expansion by using %.Ns for some N, or %.*s

The "obvious" solution to the overflow problem is a length- limited version of sprintf(), namely snprintf(). It would be used like this:
snprintf(buf, bufsize, "You typed \"%s\"", answer);
snprintf() has been available in several stdio libraries (including GNU and 4.4bsd) for several years. It will be standardized in C9X.

When the C9X snprintf() arrives, it will also be possible to use it to predict the size required for an arbitrary sprintf() call. C9X snprintf() will return the number of characters it would have placed in the buffer, not just how many it did place. Furthermore, it may be called with a buffer size of 0 and a null pointer as the destination buffer. Therefore, the call
nch = snprintf(NULL, 0, fmtstring, /* other arguments */ );
will compute the number of characters required for the fully- formatted string.

17. Why does everyone say not to use gets()?
A: Unlike fgets(), gets() cannot be told the size of the buffer it's to read into, so it cannot be prevented from overflowing that buffer. As a general rule, always use fgets().

18. Why does errno contain ENOTTY after a call to printf()?
A: Many implementations of the stdio package adjust their behavior slightly if stdout is a terminal. To make the determination, these implementations perform some operation which happens to fail (with ENOTTY) if stdout is not a terminal. Although the output operation goes on to complete successfully, errno still contains ENOTTY. (Note that it is only meaningful for a program to inspect the contents of errno after an error has been reported; errno is not guaranteed to be 0 otherwise.)

19. What's the difference between fgetpos/fsetpos and ftell/fseek? What are fgetpos() and fsetpos() good for?
A: ftell() and fseek() use type long int to represent offsets (positions) in a file, and may therefore be limited to offsets of about 2 billion (2**31-1). The newer fgetpos() and fsetpos() functions, on the other hand, use a special typedef, fpos_t, to represent the offsets. The type behind this typedef, if chosen appropriately, can represent arbitrarily large offsets, so fgetpos() and fsetpos() can be used with arbitrarily huge files. fgetpos() and fsetpos() also record the state associated with multibyte streams.

20. How can I flush pending input so that a user's typeahead isn't read at the next prompt? Will fflush(stdin) work?
A: fflush() is defined only for output streams. Since its definition of "flush" is to complete the writing of buffered characters (not to discard them), discarding unread input would not be an analogous meaning for fflush on input streams.

There is no standard way to discard unread characters from a stdio input stream, nor would such a way necessarily be sufficient, since unread characters can also accumulate in other, OS-level input buffers. You may be able to read and discard characters until \n, or use the curses flushinp()
function, or use some system-specific technique.

21. I'm trying to update a file in place, by using fopen mode "r+", reading a certain string, and writing back a modified string, but it's not working.
A: Be sure to call fseek before you write, both to seek back to the beginning of the string you're trying to overwrite, and because an fseek or fflush is always required between reading and writing in the read/write "+" modes. Also, remember that you can only overwrite characters with the same number of replacement characters, and that overwriting in text mode may truncate the file at that point.

22. How can I redirect stdin or stdout to a file from within a program?
A: Use freopen()

23. Once I've used freopen(), how can I get the original stdout (or stdin) back?
A: There isn't a good way. If you need to switch back, the best solution is not to have used freopen() in the first place. Try using your own explicit output (or input) stream variable, which you can reassign at will, while leaving the original stdout (or stdin) undisturbed.

It is barely possible to save away information about a stream before calling freopen(), such that the original stream can later be restored, but the methods involve system-specific calls such as dup(), or copying or inspecting the contents of a FILE structure, which is exceedingly nonportable and unreliable.

24. How can I arrange to have output go two places at once, e.g. to the screen and to a file?
A: You can't do this directly, but you could write your own printf variant which printed everything twice.

25. How can I read a binary data file properly? I'm occasionally seeing 0x0a and 0x0d values getting garbled, and I seem to hit EOF prematurely if the data contains the value 0x1a.
A: When you're reading a binary data file, you should specify "rb" mode when calling fopen(), to make sure that text file translations do not occur. Similarly, when writing binary data files, use "wb".

Note that the text/binary distinction is made when you open the file: once a file is open, it doesn't matter which I/O calls you use on it.

ANSI C technical interview questions and Notes -12

ANSI Standard C Project Notes and Technical Developers / Coders Job Interview Enquiry Questions and Answers with solutions of programs.

1. What is the "ANSI C Standard?" (history)
A: In 1983, the American National Standards Institute (ANSI) commissioned a committee, X3J11, to standardize the C language. After a long, arduous process, including several widespread public reviews, the committee's work was finally ratified as ANS X3.159-1989 on December 14, 1989, and published in the spring of 1990. For the most part, ANSI C standardizes existing practice, with a few additions from C++ (most notably function prototypes) and support for multinational character sets (including the controversial trigraph sequences). The ANSI C standard also formalizes the C run-time library support routines.

More recently, the Standard has been adopted as an international standard, ISO/IEC 9899:1990, and this ISO Standard replaces the earlier X3.159 even within the United States (where it is known
as ANSI/ISO 9899-1990 [1992]). As an ISO Standard, it is subject to ongoing revision through the release of Technical Corrigenda and Normative Addenda.

In 1994, Technical Corrigendum 1 (TC1) amended the Standard in about 40 places, most of them minor corrections or clarifications, and Normative Addendum 1 (NA1) added about 50 pages of new material, mostly specifying new library functions for internationalization. In 1995, TC2 added a few more minor corrections.

As of this writing, a complete revision of the Standard is in its final stages. The new Standard is nicknamed "C9X" on the assumption that it will be finished by the end of 1999. (Many of this article's answers have been updated to reflect new C9X features.)

The original ANSI Standard included a "Rationale," explaining many of its decisions, and discussing a number of subtle points, including several of those covered here. (The Rationale was "not part of ANSI Standard X3.159-1989, but... included for information only," and is not included with the ISO Standard. A new one is being prepared for C9X.)

2. How can I get a copy of the Standard?
A: Copies are available in the United States from
American National Standards Institute
11 W. 42nd St., 13th floor
New York, NY 10036 USA
(+1) 212 642 4900

and

Global Engineering Documents
15 Inverness Way E
Englewood, CO 80112 USA
(+1) 303 397 2715
(800) 854 7179 (U.S. & Canada)

In other countries, contact the appropriate national standards
body, or ISO in Geneva at:

ISO Sales
Case Postale 56
CH-1211 Geneve 20
Switzerland

Or Visit
WWW.ISO.CH

3. Where can I get information about updates to the Standard?
A: You can find information (including C9X drafts) at the web site
http://www.dmk.com/

4.My ANSI compiler complains about a mismatch when it sees
extern int func(float);
int func(x)
float x;
{ ...

A: You have mixed the new-style prototype declaration "extern int func(float);" with the old-style definition "int func(x) float x;". It is usually possible to mix the two styles, but not in this case.

Old C (and ANSI C, in the absence of prototypes, and in variable- length argument lists;) "widens" certain arguments when they are passed to functions. floats are promoted to double, and characters and short integers are promoted to int. (For old-style function definitions, the values are automatically converted back to the corresponding narrower types within the body of the called function, if they are declared that way there.)

This problem can be fixed either by using new-style syntax consistently in the definition:
int func(float x) { ... }
or by changing the new-style prototype declaration to match the old-style definition:
extern int func(double);
(In this case, it would be clearest to change the old-style definition to use double as well, if possible.)
It is arguably much safer to avoid "narrow" (char, short int, and float) function arguments and return types altogether.

5. Can you mix old-style and new-style function syntax?
A: Doing so is legal, but requires a certain amount of care. Modern practice, however, is to use the prototyped form in both declarations and definitions. (The old-style syntax is marked as obsolescent, so official support for it may be removed some day.)

6. Why does the declaration
extern int f(struct x *p);
give me an obscure warning message about "struct x introduced in prototype scope"?

A: In a quirk of C's normal block scoping rules, a structure declared (or even mentioned) for the first time within a prototype cannot be compatible with other structures declared in the same source file (it goes out of scope at the end of the prototype).

To resolve the problem, precede the prototype with the vacuous- looking declaration
struct x;
which places an (incomplete) declaration of struct x at file scope, so that all following declarations involving struct x can at least be sure they're referring to the same struct x.

7. I don't understand why I can't use const values in initializers and array dimensions, as in
const int n = 5;
int a[n];
A: The const qualifier really means "read-only"; an object so qualified is a run-time object which cannot (normally) be assigned to. The value of a const-qualified object is therefore *not* a constant expression in the full sense of the term. (C is unlike C++ in this regard.) When you need a true compile- time constant, use a preprocessor #define (or perhaps an enum).

8. What's the difference between "const char *p" and "char * const p"?
A: "const char *p" (which can also be written "char const *p") declares a pointer to a constant character (you can't change the character); "char * const p" declares a constant pointer to a (variable) character (i.e. you can't change the pointer).

9. Why can't I pass a char ** to a function which expects a const char **?
A: You can use a pointer-to-T (for any type T) where a pointer-to- const-T is expected. However, the rule (an explicit exception) which permits slight mismatches in qualified pointer types is not applied recursively, but only at the top level.

You must use explicit casts (e.g. (const char **) in this case) when assigning (or passing) pointers which have qualifier mismatches at other than the first level of indirection.

10. What's the correct declaration of main()?
A: Either int main(), int main(void), or int main(int argc, char *argv[]) (with alternate spellings of argc and *argv[] obviously allowed).

11. Can I declare main() as void, to shut off these annoying "main returns no value" messages?
A: No. main() must be declared as returning an int, and as taking either zero or two arguments, of the appropriate types. If you're calling exit() but still getting warnings, you may have to insert a redundant return statement (or use some kind of "not reached" directive, if available).

Declaring a function as void does not merely shut off or rearrange warnings: it may also result in a different function call/return sequence, incompatible with what the caller (in main's case, the C run-time startup code) expects.

(Note that this discussion of main() pertains only to "hosted" implementations; none of it applies to "freestanding" implementations, which may not even have main(). However, freestanding implementations are comparatively rare, and if you're using one, you probably know it. If you've never heard of the distinction, you're probably using a hosted implementation, and the above rules apply.)

12. But what about main's third argument, envp?
A: It's a non-standard (though common) extension. If you really need to access the environment in ways beyond what the standard getenv() function provides, though, the global variable environ is probably a better avenue (though it's equally non-standard).

13. I believe that declaring void main() can't fail, since I'm calling exit() instead of returning, and anyway my operating system ignores a program's exit/return status.
A: It doesn't matter whether main() returns or not, or whether anyone looks at the status; the problem is that when main() is misdeclared, its caller (the runtime startup code) may not even
be able to *call* it correctly (due to the potential clash of calling conventions; ).

It has been reported that programs using void main() and compiled using BC++ 4.5 can crash. Some compilers (including DEC C V4.1 and gcc with certain warnings enabled) will complain
about void main().

Your operating system may ignore the exit status, and void main() may work for you, but it is not portable and not correct.

14. The book I've been using, _C Programing for the Compleat Idiot_, always uses void main().
A: Perhaps its author counts himself among the target audience. Many books unaccountably use void main() in examples, and assert that it's correct. They're wrong.

15.Is exit(status) truly equivalent to returning the same status from main()?
A: Yes and no. The Standard says that they are equivalent. However, a return from main() cannot be expected to work if data local to main() might be needed during cleanup; A few very old, nonconforming systems may once have had problems with one or the other form. (Finally, the
two forms are obviously not equivalent in a recursive call to main().)

16. I'm trying to use the ANSI "stringizing" preprocessing operator `#' to insert the value of a symbolic constant into a message, but it keeps stringizing the macro's name rather than its value.
A: You can use something like the following two-step procedure to force a macro to be expanded as well as stringized:
#define Str(x) #x
#define Xstr(x) Str(x)
#define OP plus
char *opname = Xstr(OP);

This code sets opname to "plus" rather than "OP".
An equivalent circumlocution is necessary with the token-pasting operator ## when the values (rather than the names) of two macros are to be concatenated.

17. What does the message "warning: macro replacement within a string literal" mean?
A: Some pre-ANSI compilers/preprocessors interpreted macro definitions like
#define TRACE(var, fmt) printf("TRACE: var = fmt\n", var)
such that invocations like
TRACE(i, %d);
were expanded as
printf("TRACE: i = %d\n", i);
In other words, macro parameters were expanded even inside string literals and character constants.
Macro expansion is *not* defined in this way by K&R or by Standard C. When you do want to turn macro arguments into strings, you can use the new # preprocessing operator, along
with string literal concatenation (another new ANSI feature):
#define TRACE(var, fmt) \
printf("TRACE: " #var " = " #fmt "\n", var)

18. I'm getting strange syntax errors inside lines I've #ifdeffed out.
A: Under ANSI C, the text inside a "turned off" #if, #ifdef, or #ifndef must still consist of "valid preprocessing tokens." This means that the characters " and ' must each be paired just as in real C code, and the pairs mustn't cross line boundaries. (Note particularly that an apostrophe within a contracted word looks like the beginning of a character constant.) Therefore, natural-language comments and pseudocode should always be written between the "official" comment delimiters /* and */.

19. What are #pragmas and what are they good for?
A: The #pragma directive provides a single, well-defined "escape hatch" which can be used for all sorts of (nonportable) implementation-specific controls and extensions: source listing control, structure packing, warning suppression (like lint's old /* NOTREACHED */ comments), etc.

20. What does "#pragma once" mean? I found it in some header files.
A: It is an extension implemented by some preprocessors to help make header files idempotent; it is equivalent to the #ifndef , though less portable.

21. Is char a[3] = "abc"; legal? What does it mean?
A: It is legal in ANSI C (and perhaps in a few pre-ANSI systems), though useful only in rare circumstances. It declares an array of size three, initialized with the three characters 'a', 'b', and 'c', *without* the usual terminating '\0' character. The array is therefore not a true C string and cannot be used with strcpy, printf %s, etc.

Most of the time, you should let the compiler count the initializers when initializing arrays (in the case of the initializer "abc", of course, the computed size will be 4).

22. Why can't I perform arithmetic on a void * pointer?
A: The compiler doesn't know the size of the pointed-to objects. Before performing arithmetic, convert the pointer either to char * or to the pointer type you're trying to manipulate.

23. What's the difference between memcpy() and memmove()?
A: memmove() offers guaranteed behavior if the source and destination arguments overlap. memcpy() makes no such guarantee, and may therefore be more efficiently implementable. When in doubt, it's safer to use memmove().

24. What should malloc(0) do? Return a null pointer or a pointer to 0 bytes?
A: The ANSI/ISO Standard says that it may do either; the behavior is implementation-defined .

25. Why does the ANSI Standard not guarantee more than six case- insensitive characters of external identifier significance?
A: The problem is older linkers which are under the control of neither the ANSI/ISO Standard nor the C compiler developers on the systems which have them. The limitation is only that identifiers be *significant* in the first six characters, not that they be restricted to six characters in length. This
limitation is marked in the Standard as "obsolescent", and will be removed in C9X.

26. My compiler is rejecting the simplest possible test programs, with all kinds of syntax errors. Why ?
A: Perhaps it is a pre-ANSI compiler, unable to accept function prototypes and the like.

27. Why are some ANSI/ISO Standard library functions showing up as undefined, even though I've got an ANSI compiler?
A: It's possible to have a compiler available which accepts ANSI syntax, but not to have ANSI-compatible header files or run-time libraries installed. (In fact, this situation is rather common when using a non-vendor-supplied compiler such as gcc.)

28. Does anyone have a tool for converting old-style C programs toANSI C, or vice versa, or for automatically generating prototypes?
A: Two programs, protoize and unprotoize, convert back and forth between prototyped and "old style" function definitions and declarations. (These programs do *not* handle full-blown translation between "Classic" C and ANSI C.) These programs are part of the FSF's GNU C compiler distribution;

The unproto program is a filter which sits between the preprocessor and the next compiler pass, converting most of ANSI C to traditional C on-the-fly.

The GNU GhostScript package comes with a little program called ansi2knr.

Before converting ANSI C back to old-style, beware that such a conversion cannot always be made both safely and automatically. ANSI C introduces new features and complexities not found in K&R
C. You'll especially need to be careful of prototyped function calls; you'll probably need to insert explicit casts.

29. Why won't the Frobozz Magic C Compiler, which claims to be ANSI compliant, accept this code? I know that the code is ANSI, because gcc accepts it.
A: Many compilers support a few non-Standard extensions, gcc more so than most. Are you sure that the code being rejected doesn't rely on such an extension? It is usually a bad idea to perform
experiments with a particular compiler to determine properties of a language; the applicable standard may permit variations, or the compiler may be wrong.

30. People seem to make a point of distinguishing between implementation-defined, unspecified, and undefined behavior. What's the difference?
A: Briefly: implementation-defined means that an implementation must choose some behavior and document it. Unspecified means that an implementation should choose some behavior, but need not
document it. Undefined means that absolutely anything might happen. In no case does the Standard impose requirements; in the first two cases it occasionally suggests (and may require a choice from among) a small set of likely behaviors.

Note that since the Standard imposes *no* requirements on the behavior of a compiler faced with an instance of undefined behavior, the compiler can do absolutely anything. In particular, there is no guarantee that the rest of the program will perform normally. It's perilous to think that you can tolerate undefined behavior in a program;

If you're interested in writing portable code, you can ignore the distinctions, as you'll want to avoid code that depends on any of the three behaviors.

31. I'm appalled that the ANSI Standard leaves so many issues undefined. Isn't a Standard's whole job to standardize these things?
A: It has always been a characteristic of C that certain constructs behaved in whatever way a particular compiler or a particular piece of hardware chose to implement them. This deliberate imprecision often allows compilers to generate more efficient code for common cases, without having to burden all programs with extra code to assure well-defined behavior of cases deemed
to be less reasonable. Therefore, the Standard is simply codifying existing practice.

A programming language standard can be thought of as a treaty between the language user and the compiler implementor. Parts of that treaty consist of features which the compiler implementor agrees to provide, and which the user may assume will be available. Other parts, however, consist of rules which the user agrees to follow and which the implementor may assume will be followed. As long as both sides uphold their guarantees, programs have a fighting chance of working correctly. If *either* side reneges on any of its commitments, nothing is guaranteed to work.

32. People keep saying that the behavior of i = i++ is undefined, but I just tried it on an ANSI-conforming compiler, and got the results I expected.
A: A compiler may do anything it likes when faced with undefined behavior (and, within limits, with implementation-defined and unspecified behavior), including doing what you expect. It's unwise to depend on it, though.

C language latest notes and Technical Interview Questions - 11

C Preprocessor

1. How can we write a generic macro to swap two values?
A: There is no good answer to this question. If the values are integers, a well-known trick using exclusive-OR could perhaps be used, but it will not work for floating-point values or pointers, or if the two values are the same variable. If the macro is intended to be used on values of arbitrary type (the usual goal), it cannot use a temporary, since it does not know what type of temporary it needs (and would have a hard time picking a name for it if it did), and standard C does not provide a typeof operator.
The best all-around solution is probably to forget about using a macro, unless you're willing to pass in the type as a third argument.

2. What's the best way to write a multi-statement macro?
A: The usual goal is to write a macro that can be invoked as if it were a statement consisting of a single function call. This means that the "caller" will be supplying the final semicolon, so the macro body should not. The macro body cannot therefore be a simple brace-enclosed compound statement, because syntax errors would result if it were invoked (apparently as a single statement, but with a resultant extra semicolon) as the if branch of an if/else statement with an explicit else clause.

The traditional solution, therefore, is to use
#define MACRO(arg1, arg2) do { \
/* declarations */ \
stmt1; \
stmt2; \
/* ... */ \
} while(0) /* (no trailing ; ) */

When the caller appends a semicolon, this expansion becomes a single statement regardless of context. (An optimizing compiler will remove any "dead" tests or branches on the constant condition 0, although lint may complain.)

If all of the statements in the intended macro are simple expressions, with no declarations or loops, another technique is to write a single, parenthesized expression using one or more comma operators. (For an example, see the first DEBUG() macro in question 10.26.) This technique also allows a value to be "returned."

3. I'm splitting up a program into multiple source files for the first time, and I'm wondering what to put in .c files and what to put in .h files. (What does ".h" mean, anyway?)
A: As a general rule, you should put these things in header (.h) files:
macro definitions (preprocessor #defines)
structure, union, and enumeration declarations
typedef declarations
external function declarations
global variable declarations

It's especially important to put a declaration or definition in a header file when it will be shared between several other files.

On the other hand, when a definition or declaration should remain private to one .c file, it's fine to leave it there.

4. Is it acceptable for one header file to #include another?
A: It's a question of style, and thus receives considerable debate. Many people believe that "nested #include files" are to be avoided: the prestigious Indian Hill Style Guide disparages them; they can make it harder to find relevant definitions; they can lead to multiple-definition errors if a file is #included twice; and they make manual Makefile maintenance very difficult. On the other hand, they make it possible to use header files in a modular way (a header file can #include what it needs itself, rather than requiring each #includer to do so); a tool like grep (or a tags file) makes it easy to find definitions no matter where they are; a popular trick along the lines of:

#ifndef HFILENAME_USED
#define HFILENAME_USED
...header file contents...
#endif

(where a different bracketing macro name is used for each header file) makes a header file "idempotent" so that it can safely be #included multiple times; and automated Makefile maintenance
tools (which are a virtual necessity in large projects anyway; handle dependency generation in the face of nested #include files easily.

5. What's the difference between #include <> and #include "" ?
A: The <> syntax is typically used with Standard or system-supplied headers, while "" is typically used for a program's own header files.

6. What are the complete rules for header file searching?
A: The exact behavior is implementation-defined (which means that it is supposed to be documented;).
Typically, headers named with <> syntax are searched for in one or more standard places. Header files named with "" syntax are first searched for in the "current directory," then (if not found) in the same standard places.

Traditionally (especially under Unix compilers), the current directory is taken to be the directory containing the file containing the #include directive. Under other compilers, however, the current directory (if any) is the directory in which the compiler was initially invoked. Check your compiler
documentation.

7. I'm getting strange syntax errors on the very first declaration in a file, but it looks fine.
A: Perhaps there's a missing semicolon at the end of the last declaration in the last header file you're #including.

8. I seem to be missing the system header file . Can someone send me a copy?
A: Standard headers exist in part so that definitions appropriate to your compiler, operating system, and processor can be supplied. You cannot just pick up a copy of someone else's header file and expect it to work, unless that person is using exactly the same environment. Ask your compiler vendor why the file was not provided (or to send a replacement copy).

9. How can I construct preprocessor #if expressions which compare strings?
A: You can't do it directly; preprocessor #if arithmetic uses only integers. An alternative is to #define several macros with symbolic names and distinct integer values, and implement conditionals on those.

10. Does the sizeof operator work in preprocessor #if directives?
A: No. Preprocessing happens during an earlier phase of compilation, before type names have been parsed. Instead of sizeof, consider using the predefined constants in ANSI's <limits.h>, if applicable, or perhaps a "configure" script. (Better yet, try to write code which is inherently insensitive to type sizes; .)

11. Can I use an #ifdef in a #define line, to define something two different ways?
A: No. You can't "run the preprocessor on itself," so to speak. What you can do is use one of two completely separate #define lines, depending on the #ifdef setting.

12. Is there anything like an #ifdef for typedefs?
A: Unfortunately, no. You may have to keep sets of preprocessor macros (e.g. MY_TYPE_DEFINED) recording whether certain typedefs have been declared.

13. How can I use a preprocessor #if expression to tell if a machine is big-endian or little-endian?
A: You probably can't. (Preprocessor arithmetic uses only long integers, and there is no concept of addressing.) Are you sure you need to know the machine's endianness explicitly? Usually it's better to write code which doesn't care.

14. I inherited some code which contains far too many #ifdef's for my taste. How can I preprocess the code to leave only one conditional compilation set, without running it through the preprocessor and expanding all of the #include's and #define's as well?
A: There are programs floating around called unifdef, rmifdef, and scpp ("selective C preprocessor") which do exactly this.

15.: How can I list all of the predefined identifiers?
A: There's no standard way, although it is a common need. gcc provides a -dM option which works with -E, and other compilers may provide something similar. If the compiler documentation is unhelpful, the most expedient way is probably to extract printable strings from the compiler or preprocessor executable with something like the Unix strings utility. Beware that many traditional system-specific predefined identifiers (e.g. "unix") are non-Standard (because they clash with the user's namespace) and are being removed or renamed.

16. I have some old code that tries to construct identifiers with a macro like
#define Paste(a, b) a/**/b
but it doesn't work any more.
: It was an undocumented feature of some early preprocessor
implementations (notably John Reiser's) that comments
disappeared entirely and could therefore be used for token
pasting. ANSI affirms (as did K&R1) that comments are replaced
with white space. However, since the need for pasting tokens
was demonstrated and real, ANSI introduced a well-defined token-
pasting operator, ##, which can be used like this:

#define Paste(a, b) a##b

17. Why is the macro
#define TRACE(n) printf("TRACE: %d\n", n)
giving me the warning "macro replacement within a string literal"?

It seems to be expanding
TRACE(count);
as
printf("TRACE: %d\count", count);

18: I've got this tricky preprocessing I want to do and I can't figure out a way to do it.
A: C's preprocessor is not intended as a general-purpose tool. (Note also that it is not guaranteed to be available as a separate program.) Rather than forcing it to do something inappropriate, consider writing your own little special-purpose preprocessing tool, instead. You can easily get a utility like
make(1) to run it for you automatically.

If you are trying to preprocess something other than C, consider using a general-purpose preprocessor. (One older one available on most Unix systems is m4.)

19. How can I write a macro which takes a variable number of arguments?
A: One popular trick is to define and invoke the macro with a single, parenthesized "argument" which in the macro expansion becomes the entire argument list, parentheses and all, for a function such as

printf(): #define DEBUG(args) (printf("DEBUG: "), printf args)
if(n != 0) DEBUG(("n is %d\n", n));
The obvious disadvantage is that the caller must always remember to use the extra parentheses.

gcc has an extension which allows a function-like macro to accept a variable number of arguments, but it's not standard. Other possible solutions are to use different macros (DEBUG1, DEBUG2, etc.) depending on the number of arguments, or to play tricky games with commas:

#define DEBUG(args) (printf("DEBUG: "), printf(args))
#define _ ,
DEBUG("i = %d" _ i)

C9X will introduce formal support for function-like macros with variable-length argument lists. The notation ... will appear at the end of the macro "prototype" (just as it does for varargs functions), and the pseudomacro __VA_ARGS__ in the macro definition will be replaced by the variable arguments during invocation.

Finally, you can always use a bona-fide function, which can take a variable number of arguments in a well-defined way. (If you needed a macro replacement, try using a function plus a non-function-like
macro, e.g. #define printf myprintf .)

C language Technical Interview Questions and Project Notes / topics - 10

Characters and Strings

1. Why doesn't
strcat(string, '!');
work?
A: There is a very real difference between characters and strings, and strcat() concatenates *strings*.
Characters in C are represented by small integers corresponding to their character set values.
Strings are represented by arrays of characters; you usually manipulate a pointer to the first character of the array. It is never correct to use one when the other is expected. To append
a ! to a string, use
strcat(string, "!");

2. I'm checking a string to see if it matches a particular value. Why isn't this code working?
char *string;
...
if(string == "value") {
/* string matches "value" */
...
}
A: Strings in C are represented as arrays of characters, and C never manipulates (assigns, compares, etc.) arrays as a whole. The == operator in the code fragment above compares two pointers -- the value of the pointer variable string and a pointer to the string literal "value" -- to see if they are equal, that is, if they point to the same place. They probably don't, so the comparison never succeeds.

To compare two strings, you generally use the library function strcmp():

if(strcmp(string, "value") == 0) {
/* string matches "value" */
...
}

3. If I can say
char a[] = "Hello, world!";
why can't I say
char a[14];
a = "Hello, world!";
A: Strings are arrays, and you can't assign arrays directly. Use strcpy() instead:
strcpy(a, "Hello, world!");

4. How can I get the numeric (character set) value corresponding to a character, or vice versa?
A: In C, characters are represented by small integers corresponding to their values (in the machine's character set), so you don't need a conversion function: if you have the character, you have its value.

5. I think something's wrong with my compiler: I just noticed that sizeof('a') is 2, not 1 (i.e. not sizeof(char)).
A: Perhaps surprisingly, character constants in C are of type int, so sizeof('a') is sizeof(int) (though this is another area where C++ differs).

Boolean Expressions and Variables

1. What is the right type to use for Boolean values in C? Why isn't it a standard type? Should I use #defines or enums for the true and false values?
A: C does not provide a standard Boolean type, in part because picking one involves a space/time tradeoff which can best be decided by the programmer. (Using an int may be faster, while using char may save data space. Smaller types may make the generated code bigger or slower, though, if they require lots of conversions to and from int.)

The choice between #defines and enumeration constants for the true/false values is arbitrary and not terribly interesting . Use any of
#define TRUE 1 #define YES 1
#define FALSE 0 #define NO 0
enum bool {false, true}; enum bool {no, yes};
or use raw 1 and 0, as long as you are consistent within one program or project. (An enumeration may be preferable if your debugger shows the names of enumeration constants when examining
variables.)
Some people prefer variants like
#define TRUE (1==1)
#define FALSE (!TRUE)
or define "helper" macros such as
#define Istrue(e) ((e) != 0)
These don't buy anything.

2. Isn't #defining TRUE to be 1 dangerous, since any nonzero value is considered "true" in C? What if a built-in logical or relational operator "returns" something other than 1?
A: It is true (sic) that any nonzero value is considered true in C, but this applies only "on input", i.e. where a Boolean value is expected. When a Boolean value is generated by a built-in operator, it is guaranteed to be 1 or 0. Therefore, the test
if((a == b) == TRUE)
would work as expected (as long as TRUE is 1), but it is obviously silly. In fact, explicit tests against TRUE and FALSE are generally inappropriate, because some library functions (notably isupper(), isalpha(), etc.) return, on success, a nonzero value which is not necessarily 1.
(Besides, if you believe that "if((a == b) == TRUE)" is an improvement over "if(a == b)", why stop there? Why not use "if(((a == b) == TRUE) == TRUE)"?) A good rule of thumb is to use TRUE and FALSE (or the like) only for assignment to a Boolean variable or function parameter, or as the return
value from a Boolean function, but never in a comparison.
The preprocessor macros TRUE and FALSE (and, of course, NULL) are used for code readability, not because the underlying values might ever change.
Although the use of macros like TRUE and FALSE (or YES and NO) seems clearer, Boolean values and definitions can be sufficiently confusing in C that some programmers feel that TRUE and FALSE macros only compound the confusion, and prefer to use raw 1 and 0 instead.

C language latest and recent interview questions for 2008 asked in latest placement papers of leading companies in India, USA, etc. Project notes for students /college admission interviews, important basic free download programs with detailed answers and solutions for freshers and walkins for all university bca, btech, engineering, computer applications, developers jobs, etc.

C language Questions and answers - 9

Memory Allocation Strategy and c language Programs

1. Why doesn't this fragment work?
char *answer;
printf("Type something:\n");
gets(answer);
printf("You typed \"%s\"\n", answer);

A: The pointer variable answer, which is handed to gets() as the location into which the response should be stored, has not been set to point to any valid storage. That is, we cannot say where
the pointer answer points. (Since local variables are not initialized, and typically contain garbage, it is not even guaranteed that answer starts out as a null pointer.

The simplest way to correct the question-asking program is to use a local array, instead of a pointer, and let the compiler worry about allocation:

#include
#include

char answer[100], *p;
printf("Type something:\n");
fgets(answer, sizeof answer, stdin);
if((p = strchr(answer, '\n')) != NULL)
*p = '\0';
printf("You typed \"%s\"\n", answer);

This example also uses fgets() instead of gets(), so that the end of the array cannot be overwritten. Unfortunately for this example, fgets() does not automatically delete the trailing \n, as gets() would.) It would also be possible to use malloc() to allocate the answer buffer.

2. I can't get strcat() to work. I tried
char *s1 = "Hello, ";
char *s2 = "world!";
char *s3 = strcat(s1, s2);
but I got strange results.Why ?

A: As in question 1 above, the main problem here is that spacefor the concatenated result is not properly allocated. C does not provide an automatically-managed string type. C compilers only allocate memory for objects explicitly mentioned in the source code (in the case of strings, this includes character arrays and string literals). The programmer must arrange for sufficient space for the results of run-time operations such as string concatenation, typically by declaring arrays, or by
calling malloc().

strcat() performs no allocation; the second string is appended to the first one, in place. Therefore, one fix would be to declare the first string as an array:

char s1[20] = "Hello, ";

Since strcat() returns the value of its first argument (s1, in this case), the variable s3 is superfluous; after the call to strcat(), s1 contains the result.

The original call to strcat() in the question actually has two problems: the string literal pointed to by s1, besides not being big enough for any concatenated text, is not necessarily writable at all.

3. But the man page for strcat() says that it takes two char *'s as arguments. How am I supposed to know to allocate things?
A: In general, when using pointers you *always* have to consider memory allocation, if only to make sure that the compiler is doing it for you. If a library function's documentation does not explicitly mention allocation, it is usually the caller's problem.

The Synopsis section at the top of a Unix-style man page or in the ANSI C standard can be misleading. The code fragments presented there are closer to the function definitions used by
an implementor than the invocations used by the caller. In particular, many functions which accept pointers (e.g. to structures or strings) are usually called with a pointer to some object (a structure, or an array ) which the caller has allocated. Other common examples are time() and stat().

4. I just tried the code
char *p;
strcpy(p, "abc");
and it worked. How? Why didn't it crash?
A: You got lucky, I guess. The memory pointed to by the unitialized pointer p happened to be writable by you, and apparently was not already in use for anything vital.

5.How much memory does a pointer variable allocate?
A: That's a pretty misleading question. When you declare a pointer variable, as in

char *p;

you (or, more properly, the compiler) have allocated only enough memory to hold the pointer itself; that is, in this case you have allocated sizeof(char *) bytes of memory. But you have not yet allocated *any* memory for the pointer to point to.

6.I have a function that is supposed to return a string, but when it returns to its caller, the returned string is garbage.
A: Make sure that the pointed-to memory is properly allocated. For example, make sure you have *not* done something like

char *itoa(int n)
{
char retbuf[20]; /* WRONG */
sprintf(retbuf, "%d", n);
return retbuf; /* WRONG */
}

One fix (which is imperfect, especially if the function in question is called recursively, or if several of its return values are needed simultaneously) would be to declare the return buffer as

static char retbuf[20];

7. So what's the right way to return a string or other aggregate?
A: The returned pointer should be to a statically-allocated buffer, or to a buffer passed in by the caller, or to memory obtained with malloc(), but *not* to a local (automatic) array.

8. Why am I getting "warning: assignment of pointer from integer lacks a cast" for calls to malloc()?
A: Have you #include, or otherwise arranged for malloc() to be declared properly.

9. Why does some code carefully cast the values returned by malloc to the pointer type being allocated?
A: Before ANSI/ISO Standard C introduced the void * generic pointer type, these casts were typically required to silence warnings (and perhaps induce conversions) when assigning between incompatible pointer types.

Under ANSI/ISO Standard C, these casts are no longer necessary, and in fact modern practice discourages them, since they can camouflage important warnings which would otherwise be generated if malloc() happened not to be declared correctly; (However, the casts are typically seen in C code which for one reason or another is intended to be compatible with C++, where explicit casts from void * are required.)

10. I see code like
char *p = malloc(strlen(s) + 1);
strcpy(p, s);
Shouldn't that be malloc((strlen(s) + 1) * sizeof(char))?
A: It's never necessary to multiply by sizeof(char), since sizeof(char) is, by definition, exactly 1. (On the other hand, multiplying by sizeof(char) doesn't hurt, and in some circumstances may help by introducing a size_t into the expression.)

11. I've heard that some operating systems don't actually allocate memory until the program tries to use it. Is this legal?
A: It's hard to say. The Standard doesn't say that systems can act this way, but it doesn't explicitly say that they can't, either.

12. I'm allocating a large array for some numeric work, using the line
double *array = malloc(300 * 300 * sizeof(double));
malloc() isn't returning null, but the program is acting strangely, as if it's overwriting memory, or malloc() isn't allocating as much as I asked for, or something.
A: Notice that 300 x 300 is 90,000, which will not fit in a 16-bit int, even before you multiply it by sizeof(double). If you need to allocate this much memory, you'll have to be careful. If size_t (the type accepted by malloc()) is a 32-bit type on your machine, but int is 16 bits, you might be able to get away with writing 300 * (300 * sizeof(double)). Otherwise, you'll have to break your data structure up into smaller chunks, or use a 32-bit machine or compiler, or use some nonstandard memory allocation functions.

13.I've got 8 meg of memory in my PC. Why can I only seem to malloc 640K or so?
A: Under the segmented architecture of PC compatibles, it can be difficult to use more than 640K with any degree of transparency, especially under MS-DOS.

14. My program is crashing, apparently somewhere down inside malloc, but I can't see anything wrong with it. Is there a bug in malloc()?
A: It is unfortunately very easy to corrupt malloc's internal data structures, and the resulting problems can be stubborn. The most common source of problems is writing more to a malloc'ed
region than it was allocated to hold; a particularly common bug is to malloc(strlen(s)) instead of strlen(s) + 1. Other problems may involve using pointers to memory that has been freed, freeing pointers twice, freeing pointers not obtained from malloc, or trying to realloc a null pointer

15. You can't use dynamically-allocated memory after you free it, can you?
A: No. Some early documentation for malloc() stated that the contents of freed memory were "left undisturbed," but this ill- advised guarantee was never universal and is not required by the C Standard.

Few programmers would use the contents of freed memory deliberately, but it is easy to do so accidentally. Consider the following (correct) code for freeing a singly-linked list:

struct list *listp, *nextp;
for(listp = base; listp != NULL; listp = nextp) {
nextp = listp->next;
free(listp);
}

and notice what would happen if the more-obvious loop iteration expression listp = listp->next were used, without the temporary nextp pointer.

16. Why isn't a pointer null after calling free()? How unsafe is it to use (assign, compare) a pointer value after it's been freed?
A: When you call free(), the memory pointed to by the passed pointer is freed, but the value of the pointer in the caller probably remains unchanged, because C's pass-by-value semantics mean that called functions never permanently change the values of their arguments.

A pointer value which has been freed is, strictly speaking, invalid, and *any* use of it, even if is not dereferenced, can theoretically lead to trouble, though as a quality of implementation issue, most implementations will probably not go out of their way to generate exceptions for innocuous uses of
invalid pointers.

17.When I call malloc() to allocate memory for a pointer which is local to a function, do I have to explicitly free() it?
A: Yes. Remember that a pointer is different from what it points to. Local variables are deallocated when the function returns, but in the case of a pointer variable, this means that the pointer is deallocated, *not* what it points to. Memory allocated with malloc() always persists until you explicitly free it. In general, for every call to malloc(), there should be a corresponding call to free().

18. I'm allocating structures which contain pointers to other dynamically-allocated objects. When I free a structure, do I also have to free each subsidiary pointer?
A: Yes. In general, you must arrange that each pointer returned from malloc() be individually passed to free(), exactly once (if it is freed at all). A good rule of thumb is that for each call to malloc() in a program, you should be able to point at the call to free() which frees the memory allocated by that malloc() call.

19. Must I free allocated memory before the program exits?
A: You shouldn't have to. A real operating system definitively reclaims all memory and other resources when a program exits. Nevertheless, some personal computers are said not to reliably
recover memory, and all that can be inferred from the ANSI/ISO C Standard is that this is a "quality of implementation issue."

20. I have a program which mallocs and later frees a lot of memory, but I can see from the operating system that memory usage doesn't actually go back down.
A: Most implementations of malloc/free do not return freed memory to the operating system, but merely make it available for future malloc() calls within the same program.

21. How does free() know how many bytes to free?
A: The malloc/free implementation remembers the size of each block as it is allocated, so it is not necessary to remind it of the size when freeing.

22. So can I query the malloc package to find out how big an allocated block is?
A: Unfortunately, there is no standard or portable way.

23. Is it legal to pass a null pointer as the first argument to realloc()? Why would you want to?
A: ANSI C sanctions this usage (and the related realloc(..., 0), which frees), although several earlier implementations do not support it, so it may not be fully portable. Passing an initially-null pointer to realloc() can make it easier to write a self-starting incremental allocation algorithm.

24. What's the difference between calloc() and malloc()? Is it safe to take advantage of calloc's zero-filling? Does free() work on memory allocated with calloc(), or do you need a cfree()?
A: calloc(m, n) is essentially equivalent to

p = malloc(m * n);
memset(p, 0, m * n);

The zero fill is all-bits-zero, and does *not* therefore guarantee useful null pointer values (see section 5 of this list) or floating-point zero values. free() is properly used to free the memory allocated by calloc().

25. What is alloca() and why is its use discouraged?
A: alloca() allocates memory which is automatically freed when the function which called alloca() returns. That is, memory allocated with alloca is local to a particular function's "stack frame" or context.

alloca() cannot be written portably, and is difficult to implement on machines without a conventional stack. Its use is problematical (and the obvious implementation on a stack-based machine fails) when its return value is passed directly to another function, as in fgets(alloca(100), 100, stdin).

For these reasons, alloca() is not Standard and cannot be used in programs which must be widely portable, no matter how useful it might be.