Saturday, April 5, 2014

interview questions computer C languages

http://questions-interviews.blogspot.in/2012/05/computer-programming-interview.html

What is C language? 
The C programming language is a standardized programming language developed in the early 1970s by Ken Thompson and Dennis Ritchie for use on the UNIX operating system. It has since spread to many other operating systems, and is one of the most widely used programming languages. C is prized for its efficiency, and is the most popular programming language for writing system software, though it is also used for writing applications. ...
What is Duffs Device? 
It's a devastatingly devious way of unrolling a loop, devised by Tom Duff while he was at Lucasfilm. In its ``classic'' form, it was used to copy bytes, and looked like this: register n = (count + 7) / 8; /* count > 0 assumed */ switch (count % 8) { case 0: do { *to = *from++; case 7: *to = *from++; case 6: *to = *from++; case 5: *to = *from++; case 4: *to = *from++; case 3: *to = *from++; case 2: *to = *from++; case 1: *to = *from++; } while (--n > 0); }
where count bytes are to be copied from the array pointed to by from to the memory location pointed to by to (which is a memory-mapped device output register, which is why to isn't incremented). It solves the problem of handling the leftover bytes (when count isn't a multiple of 8) by interleaving a switch statement with the loop which copies bytes 8 at a time. (Believe it or not, it is legal to have case labels buried within blocks nested in a switch statement like this. In his announcement of the technique to C's developers and the world, Duff noted that C's switch syntax, in particular its ``fall through'' behavior, had long been controversial, and that ``This code forms some sort of argument in that debate, but I'm not sure whether it's for or against.'')
Here is a good puzzle: how do you write a program which produces its own source code as output? 
It is actually quite difficult to write a self-reproducing program that is truly portable, due particularly to quoting and character set difficulties.
Here is a classic example (which ought to be presented on one line, although it will fix itself the first time it's run):
char*s="char*s=%c%s%c;main(){printf(s,34,s,34);}";
main(){printf(s,34,s,34);}

(This program has a few deficiencies, among other things neglecting to #include <stdio.h>, and assuming that the double-quote character " has the value 34, as it does in ASCII.)

#define q(k)main(){return!puts(#k"nq("#k")");}
q(#define q(k)main(){return!puts(#k"nq("#k")");})
Suggesting that there can be 62 seconds in a minute? 
Q: Why can tm_sec in the tm structure range from 0 to 61, suggesting that there can be 62 seconds in a minute?

A: That's actually a buglet in the Standard. There can be 61 seconds in a minute during a leap second. It's possible for there to be two leap seconds in a year, but it turns out that it's guaranteed that they'll never both occur in the same day (let alone the same minute).
Was 2000 a leap year? 
Is (year % 4 == 0) an accurate test for leap years? (Was 2000 a leap year?)

No, it's not accurate (and yes, 2000 was a leap year). The actual rules for the present Gregorian calendar are that leap years occur every four years, but not every 100 years, except that they do occur every 400 years, after all. In C, these rules can be expressed as:
year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
Actually, if the domain of interest is limited (perhaps by the range of a time_t) such that the only century year it encompasses is 2000, the expression
(year % 4 == 0) /* 1901-2099 only */
is accurate, if less than robust.
If you trust the implementor of the C library, you can use mktime to determine whether a given year is a leap year;
Note also that the transition from the Julian to the Gregorian calendar involved deleting several days to make up for accumulated errors. (The transition was first made in Catholic countries under Pope Gregory XIII in October, 1582, and involved deleting 10 days. In the British Empire, eleven days were deleted when the Gregorian calendar was adopted in September 1752. A few countries didn't switch until the 20th century.) Calendar code which has to work for historical dates must therefore be especially careful.
How can I find the day of the week given the date? 
Here are three methods:
1. Use mktime or localtime # . Here is a code fragment which computes the day of the week for February 29, 2000:

#include <stdio.h>
#include <time.h>

char *wday[] = {"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"};

struct tm tm;

tm.tm_mon = 2 - 1;
tm.tm_mday = 29;
tm.tm_year = 2000 - 1900;
tm.tm_hour = tm.tm_min = tm.tm_sec = 0;
tm.tm_isdst = -1;

if(mktime(&tm) != -1)
printf("%sn", wday[tm.tm_wday]);

When using mktime like this, it's usually important to set tm_isdst to -1, as shown (especially if tm_hour is 0), otherwise a daylight saving time correction could push the time past midnight into another day. # Use Zeller's congruence, which says that if

J is the number of the century [i.e. the year / 100],
K the year within the century [i.e. the year % 100],
m the month,
q the day of the month,
h the day of the week [where 1 is Sunday];
What is hashing in C? 
Hashing is the process of mapping strings to integers, usually in a relatively small range. A ``hash function'' maps a string (or some other data structure) to a bounded number (the ``hash bucket'') which can more easily be used as an index in an array, or for performing repeated comparisons. (Obviously, a mapping from a potentially huge set of strings to a small set of integers will not be unique. Any algorithm using hashing therefore has to deal with the possibility of ``collisions.'')
Many hashing functions and related algorithms have been developed; a full treatment is beyond the scope of this list. An extremely simple hash function for strings is simply to add up the values of all the characters:

unsigned hash(char *str)
{
unsigned int h = 0;
while(*str != '')
h += *str++;
return h % NBUCKETS;
}

A somewhat better hash function is

unsigned hash(char *str)
{
unsigned int h = 0;
while(*str != '')
h = (256 * h + *str++) % NBUCKETS;
return h;
}
I need a sort of an approximate strcmp routine ... 
I need a sort of an ``approximate'' strcmp routine, for comparing two strings for close, but not necessarily exact, equality.

Some nice information and algorithms having to do with approximate string matching, as well as a useful bibliography, can be found in Sun Wu and Udi Manber's paper ``AGREP--A Fast Approximate Pattern-Matching Tool.''
Another approach involves the ``soundex'' algorithm, which maps similar-sounding words to the same codes. Soundex was designed for discovering similar-sounding names (for telephone directory assistance, as it happens), but it can be pressed into service for processing arbitrary words.
What is C Programing language? 
Is C++ a superset of C? What are the differences between C and C++? Can I use a C++ compiler to compile C code?

C++ was derived from C, and is largely based on it, but there are some legal C constructs which are not legal C++. Conversely, ANSI C inherited several features from C++, including prototypes and const, so neither language is really a subset or superset of the other; the two also define the meaning of some common constructs differently.
The most important feature of C++ not found in C is of course the extended structure known as a class which along with operator overloading makes object-oriented programming convenient. There are several other differences and new features: variables may be declared anywhere in a block; const variables may be true compile-time constants; structure tags are implicitly typedeffed; an & in a parameter declaration requests pass by reference; and the new and delete operators, along with per-object constructors and destructors, simplify dynamic data structure management. There are a host of mechanisms tied up with classes and object-oriented programming: inheritance, friends, virtual functions, templates, etc. (This list of C++ features is not intended to be complete; C++ programmers will notice many omissions.)
How can I call FORTRAN? 
How can I call FORTRAN (C++, BASIC, Pascal, Ada, LISP) functions from C? (And vice versa?)

The answer is entirely dependent on the machine and the specific calling sequences of the various compilers in use, and may not be possible at all. Read your compiler documentation very carefully; sometimes there is a ``mixed-language programming guide,'' although the techniques for passing arguments and ensuring correct run-time startup are often arcane. Besides arranging calling sequences correctly, you may also have to conspire between the various languages to get aggregate data structures declared compatibly.

In C++, a "C" modifier in an external function declaration indicates that the function is to be called using C calling conventions. In Ada, you can use the Export and Convention pragmas, and types from the package Interfaces.C, to arrange for C-compatible calls, parameters, and data structures.
What is assert and when would I use it? 
It is a macro, defined in <assert.h>, for testing ``assertions''. An assertion essentially documents an assumption being made by the programmer, an assumption which, if violated, would indicate a serious programming error. For example, a function which was supposed to be called with a non-null pointer could write
assert(p != NULL);
A failed assertion terminates the program. Assertions should not be used to catch expected errors, such as malloc or fopen failures.
Why doesnt C have nested functions? 
It's not trivial to implement nested functions such that they have the proper access to local variables in the containing function(s), so they were deliberately left out of C as a simplification. (gcc does allow them, as an extension.) For many potential uses of nested functions (e.g. qsort comparison functions), an adequate if slightly cumbersome solution is to use an adjacent function with static declaration, communicating if necessary via a few static variables. (A cleaner solution, though unsupported by qsort, is to pass around a pointer to a structure containing the necessary context.)
Does C have an equivalent to Pascals with statement? 
No. The way in C to get quick and easy access to the fields of a structure is to declare a little local structure pointer variable (which, it must be admitted, is not quite as notationally convenient as a with statement and doesn't save quite as many keystrokes, though it is probably safer). That is, if you have something unwieldy like
structarray[complex_expression].a =
structarray[complex_expression].b +
structarray[complex_expression].c;

you can replace it with

struct whatever *p = &structarray[complex_expression];
p->a = p->b + p->c;
If the assignment operator were ... 
If the assignment operator were :=, wouldn't it then be harder to accidentally write things like if(a = b) ?

Yes, but it would also be just a little bit more cumbersome to type all of the assignment statements which a typical program contains.
In any case, it's really too late to be worrying about this sort of thing now. The choices of = for assignment and == for comparison were made, rightly or wrongly, over two decades ago, and are not likely to be changed. (With respect to the question, many compilers and versions of lint will warn about if(a = b) and similar expressions;
As a point of historical interest, the choices were made based on the observation that assignment is more frequent than comparison, and so deserves fewer keystrokes. In fact, using = for assignment in C and its predecessor B represented a change from B's own predecessor BCPL, which did use := as its assignment operator.
Is C a great language, or what? 
Is C a great language, or what? Where else could you write something like a+++++b ?

Well, you can't meaningfully write it in C, either. The rule for lexical analysis is that at each point during a straightforward left-to-right scan, the longest possible token is determined, without regard to whether the resulting sequence of tokens makes sense. The fragment in the question is therefore interpreted as
a ++ ++ + b
and cannot be parsed as a valid expression.
Does C have circular shift operators? 
No. (Part of the reason why is that the sizes of C's types aren't precisely defined----but a circular shift makes most sense when applied to a word of a particular known size.)
You can implement a circular shift using two regular shifts and a bitwise OR:
(x << 13) | (x > >3) /* circular shift left 13 in 16 bits */
There seem to be a few missing operators ... 
There seem to be a few missing operators, like ^^, &&=, and ->=.

A logical exclusive-or operator (hypothetically ``^^'') would be nice, but it couldn't possibly have short-circuiting behavior analogous to && and || Similarly, it's not clear how short-circuiting would apply to hypothetical assignment operators &&= and ||=. (It's also not clear how often &&= and ||= would actually be needed.)
Though p = p->next is an extremely common idiom for traversing a linked list, -> is not a binary arithmetic operator. A hypothetical ->= operator therefore wouldn't really fit the pattern of the other assignment operators.
You can write an exclusive-or macro in several ways:
#define XOR(a, b) ((a) && !(b) || !(a) && (b)) /* 1 */
#define XOR(a, b) (!!(a) ^ !!(b)) /* 2 */
#define XOR(a, b) (!!(a) != !!(b)) /* 3 */
#define XOR(a, b) (!(a) ^ !(b)) /* 4 */
#define XOR(a, b) (!(a) != !(b)) /* 5 */
#define XOR(a, b) ((a) ? !(b) : !!(b)) /* 6 */
Why isnt there a numbered, multi-level break statement to break out 
Why isn't there a numbered, multi-level break statement to break out of several loops at once? What am I supposed to use instead, a goto?

First, remember why it is that break and continue exist at all--they are, in effect, ``structured gotos'' used in preference to goto (and accepted as alternatives by most of those who shun goto) because they are clean and structured and pretty much restricted to a common, idiomatic usages. A hypothetical multi-level break, on the other hand, would rapidly lose the inherent cleanliness of the single break--programmers and readers of code would have to carefully count nesting levels to figure out what a given break did, and the insertion of a new intermediately-nested loop could, er, break things badly. (By this analysis, a numbered break statement can be even more confusing and error-prone than a goto/label pair.)
The right way to break out of several loops at once (which C also does not have) involves a syntax which allows the naming of loops, so that a break statement can specify the name of the loop to be broken out of.
If you do have to break out of more than one loop at once (or break out of a loop from inside a switch, where break would merely end a case label) yes, go ahead and use a goto. (But when you find the need for a multi-level break, it's often a sign that the loop should be broken out to its own function, at which point you can achieve roughly the same effect as that multi-level break by using a premature return.)
Why dont C comments nest? 
Why don't C comments nest? How am I supposed to comment out code containing comments? Are comments legal inside quoted strings?

C comments don't nest mostly because PL/I's comments, which C's are borrowed from, don't either. Therefore, it is usually better to ``comment out'' large sections of code, which might contain comments, with #ifdef or #if 0 ).
The character sequences /* and */ are not special within double-quoted strings, and do not therefore introduce comments, because a program (particularly one which is generating C code as output) might want to print them. (It is hard to imagine why anyone would want or need to place a comment inside a quoted string. It is easy to imagine a program needing to print "/*".)
Are the outer parentheses in return statements really optional? 
Yes.
Long ago, in the early days of C, they were required, and just enough people learned C then, and wrote code which is still in circulation, that the notion that they might still be required is widespread.
(As it happens, parentheses are optional with the sizeof operator, too, under certain circumstances.)
Is there a way to have non-constant case labels (i.e. ranges or arbitrary expressions)? 
No. The switch statement was originally designed to be quite simple for the compiler to translate, therefore case labels are limited to single, constant, integral expressions. You can attach several case labels to the same statement, which will let you cover a small range if you don't mind listing all cases explicitly.
If you want to select on arbitrary ranges or non-constant expressions, you'll have to use an if/else chain.
Is there a way to switch on strings? 
Not directly. Sometimes, it's appropriate to use a separate function to map strings to integer codes, and then switch on those:
#define CODE_APPLE 1
#define CODE_ORANGE 2
#define CODE_NONE 0

switch(classifyfunc(string)) {
case CODE_APPLE:
...

case CODE_ORANGE:
...

case CODE_NONE:
...
}

where classifyfunc looks something like

static struct lookuptab {
char *string;
int code;
} tab[] = {
{"apple", CODE_APPLE},
{"orange", CODE_ORANGE},
};

classifyfunc(char *string)
{
int i;
for(i = 0; i < sizeof(tab) / sizeof(tab[0]); i++)
if(strcmp(tab[i].string, string) == 0)
return tab[i].code;

return CODE_NONE;
}

Otherwise, of course, you can fall back on a conventional if/else chain:

if(strcmp(string, "apple") == 0) {
...
} else if(strcmp(string, "orange") == 0) {
...
}
Which is more efficient, a switch statement or an if else chain? 
The differences, if any, are likely to be slight. The switch statement was designed to be efficiently implementable, though the compiler may choose to use the equivalent of an if/else chain (as opposed to a compact jump table) if the case labels are sparsely distributed.
Do use switch when you can: it's certainly cleaner, and perhaps more efficient (and certainly should never be any less efficient).
How can I swap two values without using a temporary? 
The standard hoary old assembly language programmer's trick is:
a ^= b;
b ^= a;
a ^= b;

But this sort of code has little place in modern, HLL programming. Temporary variables are essentially free, and the idiomatic code using three assignments, namely
int t = a;
a = b;
b = t;

is not only clearer to the human reader, it is more likely to be recognized by the compiler and turned into the most-efficient code (e.g. perhaps even using an EXCH instruction). The latter code is obviously also amenable to use with pointers and floating-point values, unlike the XOR trick.
People claim that optimizing compilers are good and that we no longer have to write things in assembler for speed 
People claim that optimizing compilers are good and that we no longer have to write things in assembler for speed, but my compiler can't even replace i/=2 with a shift.

Was i signed or unsigned? If it was signed, a shift is not equivalent (hint: think about the result if i is negative and odd), so the compiler was correct not to use it.
I have been replacing multiplications and divisions with shift operators, because shifting is more efficient. 
This is an excellent example of a potentially risky and usually unnecessary optimization. Any compiler worthy of the name can replace a constant, power-of-two multiplication with a left shift, or a similar division of an unsigned quantity with a right shift. Furthermore, a compiler will make these optimizations only when they're correct; many programmers overlook the fact that shifting a negative value to the right is not equivalent to division. (Therefore, when you need to make sure that these optimizations are performed, you may have to declare relevant variables as unsigned.)
Are pointers really faster than arrays? 
Are pointers really faster than arrays? How much do function calls slow things down? Is ++i faster than i = i + 1?

Precise answers to these and many similar questions depend of course on the processor and compiler in use. If you simply must know, you'll have to time test programs carefully. (Often the differences are so slight that hundreds of thousands of iterations are required even to see them.
For conventional machines, it is usually faster to march through large arrays with pointers rather than array subscripts, but for some processors the reverse is true. (Better compilers should generate good code regardless of which notation you use, though it's arguably easier for a compiler to convert array indices to pointers than vice versa .)
Function calls, though obviously incrementally slower than in-line code, contribute so much to modularity and code clarity that there is rarely good reason to avoid them. (Actually, by reducing bulk, functions can improve performance.) Also, some compilers are able to expand small, critical-path functions in-line, either as an optimization or at the programmer's request.
Before rearranging expressions such as i = i + 1, remember that you are dealing with a compiler, not a keystroke-programmable calculator. Any decent compiler will generate identical code for ++i, i += 1, and i = i + 1. The reasons for using ++i or i += 1 over i = i + 1 have to do with style, not efficiency.
What is the best way of making my program efficient? 
By picking good algorithms, implementing them carefully, and making sure that your program isn't doing any extra work. For example, the most microoptimized character-copying loop in the world will be beat by code which avoids having to copy characters at all.
When worrying about efficiency, it's important to keep several things in perspective. First of all, although efficiency is an enormously popular topic, it is not always as important as people tend to think it is. Most of the code in most programs is not time-critical. When code is not time-critical, it is usually more important that it be written clearly and portably than that it be written maximally efficiently. (Remember that computers are very, very fast, and that seemingly ``inefficient'' code may be quite efficiently compilable, and run without apparent delay.)
It is notoriously difficult to predict what the ``hot spots'' in a program will be. When efficiency is a concern, it is important to use profiling software to determine which parts of the program deserve attention. Often, actual computation time is swamped by peripheral tasks such as I/O and memory allocation, which can be sped up by using buffering and caching techniques.
What is the most efficient way to count the number of bits which are set in an integer? 
Many ``bit-fiddling'' problems like this one can be sped up and streamlined using lookup tables (but see question 20.13). Here is a little function which computes the number of bits in a value, 4 bits at a time:
static int bitcounts[] =
{0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4};

int bitcount(unsigned int u)
{
int n = 0;

for(; u != 0; u >>= 4)
n += bitcounts[u & 0x0f];

return n;
}
Can I use base-2 constants (something like 0b101010)? Is there a printf format for binary? 
No, on both counts, although there are various preprocessor tricks you can try. You can convert base-2 string representations to integers with strtol. If you need to print numbers out in base 2, .
How can I convert integers to binary or hexadecimal? 
Make sure you really know what you're asking. Integers are stored internally in binary, although for most purposes it is not incorrect to think of them as being in octal, decimal, or hexadecimal, whichever is convenient. The base in which a number is expressed matters only when that number is read in from or written out to the outside world, either in the form of a source code constant or in the form of I/O performed by a program.
In source code, a non-decimal base is indicated by a leading 0 or 0x (for octal or hexadecimal, respectively). During I/O, the base of a formatted number is controlled in the printf and scanf family of functions by the choice of format specifier (%d, %o, %x, etc.) and in the strtol and strtoul functions by the third argument. During binary I/O, however, the base again becomes immaterial: if numbers are being read or written as individual bytes (typically with getc or putc), or as multi-byte words (typically with fread or fwrite), it is meaningless to ask what ``base'' they are in.
If what you need is formatted binary conversion, it's easy enough to do. Here is a little function for formatting a number in a requested base:
How do I swap bytes? 
V7 Unix had a swab function, but it seems to have been forgotten.
A problem with explicit byte-swapping code is that you have to decide whether to call it or not, based on the byte order of the data and the byte order of the machine in use.
A better solution is to define functions which convert between the known byte order of the data and the (unknown) byte order of the machine in use, and to arrange for these functions to be no-ops on those machines which already match the desired byte order. A set of such functions, introduced with the BSD networking code but now in wide use, is ntohs, htons, ntohl, and htonl. These are intended to convert between ``network'' and ``host'' byte orders, for ``short'' or ``long'' integers, where ``network'' order is always big-endian, and where ``short'' integers are always 16 bits and ``long'' integers are 32 bits. (This is not the C definition, of course, but it's compatible with the C definition) So if you know that the data you want to convert from or to is big-endian, you can use these functions. (The point is that you always call the functions, making your code much cleaner. Each function either swaps bytes if it has to, or does nothing. The decision to swap or not to swap gets made once, when the functions are implemented for a particular machine, rather than being made many times in many different calling programs.)
How can I determine whether a machines byte order is big-endian or little-endian? 
The usual techniques are to use a pointer:
int x = 1;
if(*(char *)&x == 1)
printf("little-endiann");
else printf("big-endiann");

or a union:

union {
int i;
char c[sizeof(int)];
} x;
x.i = 1;
if(x.c[0] == 1)
printf("little-endiann");
else printf("big-endiann");

(Note that there are also byte order possibilities beyond simple big-endian and little-endian
How can I implement sets or arrays of bits? 
Use arrays of char or int, with a few macros to access the desired bit in the proper cell of the array. Here are some simple macros to use with arrays of char:
#include <limits.h> /* for CHAR_BIT */

#define BITMASK(b) (1 << ((b) % CHAR_BIT))
#define BITSLOT(b) ((b) / CHAR_BIT)
#define BITSET(a, b) ((a)[BITSLOT(b)] |= BITMASK(b))
#define BITCLEAR(a, b) ((a)[BITSLOT(b)] &= ~BITMASK(b))
#define BITTEST(a, b) ((a)[BITSLOT(b)] & BITMASK(b))
#define BITNSLOTS(nb) ((nb + CHAR_BIT - 1) / CHAR_BIT)

(If you don't have <limits.h>, try using 8 for CHAR_BIT.)

Here are some usage examples. To declare an ``array'' of 47 bits:
char bitarray[BITNSLOTS(47)];

To set the 23rd bit:

BITSET(bitarray, 23);

To test the 35th bit:

if(BITTEST(bitarray, 35)) ...
To compute the union of two bit arrays and place it in a third array (with all three arrays declared as above):
for(i = 0; i < BITNSLOTS(47); i++)
array3[i] = array1[i] | array2[i];

To compute the intersection, use & instead of |.
As a more realistic example, here is a quick implementation of the Sieve of Eratosthenes, for computing prime numbers:
#include <stdio.h>
#include <string.h>

#define MAX 10000

int main()
{
char bitarray[BITNSLOTS(MAX)];
int i, j;

memset(bitarray, 0, BITNSLOTS(MAX));

for(i = 2; i < MAX; i++) {
if(!BITTEST(bitarray, i)) {
printf("%dn", i);
for(j = i + i; j < MAX; j += i)
BITSET(bitarray, j);
}
}
return 0;
}
How can I manipulate individual bits? 
Bit manipulation is straightforward in C, and commonly done. To extract (test) a bit, use the bitwise AND (&) operator, along with a bit mask representing the bit(s) you're interested in:
value & 0x04
To set a bit, use the bitwise OR (| or |=) operator:

value |= 0x04

To clear a bit, use the bitwise complement (~) and the AND (& or &=) operators:
value &= ~0x04

(The preceding three examples all manipulate the third-least significant, or 2**2, bit, expressed as the constant bitmask 0x04.)
To manipulate an arbitrary bit, use the shift-left operator (<<) to generate the mask you need:

value & (1 << bitnumber)
value |= (1 << bitnumber)
value &= ~(1 << bitnumber)

Alternatively, you may wish to precompute an array of masks:

unsigned int masks[] =
{0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80};

value & masks[bitnumber]
value |= masks[bitnumber]
value &= ~masks[bitnumber]

To avoid surprises involving the sign bit, it is often a good idea to use unsigned integral types in code which manipulates bits and bytes.
If I have a char * variable pointing to the name of a function ... 
If I have a char * variable pointing to the name of a function, how can I call that function? Code like
extern int func(int, int);
char *funcname = "func";
int r = (*funcname)(1, 2);

or
r = (*(int (*)(int, int))funcname)(1, 2);

doesn't seem to work.

By the time a program is running, information about the names of its functions and variables (the ``symbol table'') is no longer needed, and may therefore not be available. The most straightforward thing to do, therefore, is to maintain that information yourself, with a correspondence table of names and function pointers:
int one_func(), two_func();
int red_func(), blue_func();

struct { char *name; int (*funcptr)(); } symtab[] = {
"one_func", one_func,
"two_func", two_func,
"red_func", red_func,
"blue_func", blue_func,
};

Then, search the table for the name, and call via the associated function pointer, with code like this:
#include <stddef.h>
int (*findfunc(char *name))()
{
int i;

for(i = 0; i < sizeof(symtab) / sizeof(symtab[0]); i++) {
if(strcmp(name, symtab[i].name) == 0)
return symtab[i].funcptr;
}

return NULL;
}

...
char *funcname = "one_func";
int (*funcp)() = findfunc(funcname);
if(funcp != NULL)
(*funcp)();
How can I write data files which can be read on other machines with different word size, byte order, or floating point formats? 
The most portable solution is to use text files (usually ASCII), written with fprintf and read with fscanf or the like. (Similar advice also applies to network protocols.) Be skeptical of arguments which imply that text files are too big, or that reading and writing them is too slow. Not only is their efficiency frequently acceptable in practice, but the advantages of being able to interchange them easily between machines, and manipulate them with standard tools, can be overwhelming.
If you must use a binary format, you can improve portability, and perhaps take advantage of prewritten I/O libraries, by making use of standardized formats such as Sun's XDR (RFC 1014), OSI's ASN.1 (referenced in CCITT X.409 and ISO 8825 ``Basic Encoding Rules''), CDF, netCDF, or HDF.
What is the right way to use errno? 
In general, you should detect errors by checking return values, and use errno only to distinguish among the various causes of an error, such as ``File not found'' or ``Permission denied''. (Typically, you use perror or strerror to print these discriminating error messages.) It's only necessary to detect errors with errno when a function does not have a unique, unambiguous, out-of-band error return (i.e. because all of its possible return values are valid; one example is atoi). In these cases (and in these cases only; check the documentation to be sure whether a function allows this), you can detect errors by setting errno to 0, calling the function, then testing errno. (Setting errno to 0 first is important, as no library function ever does that for you.)
To make error messages useful, they should include all relevant information. Besides the strerror text derived from errno, it may also be appropriate to print the name of the program, the operation which failed (preferably in terms which will be meaningful to the user), the name of the file for which the operation failed, and, if some input file (script or source file) is being read, the name and current line number of that file.
What is a good data structure to use for storing lines of text? 
What's a good data structure to use for storing lines of text? I started to use fixed-size arrays of arrays of char, but they're just too restrictive.

One good way of doing this is with a pointer (simulating an array) to a set of pointers (each simulating an array) of char. This data structure is sometimes called a ``ragged array,'' and looks something like this:
[FIGURE GOES HERE]
You could set up the tiny array in the figure above with these simple declarations:
char *a[4] = {"this", "is", "a", "test"};
char **p = a;

(where p is the pointer-to-pointer-to-char and a is an intermediate array used to allocate the four pointers-to-char).
To really do dynamic allocation, you'd of course have to call malloc:
#include <stdlib.h>
char **p = malloc(4 * sizeof(char *));
if(p != NULL) {
p[0] = malloc(5);
p[1] = malloc(3);
p[2] = malloc(2);
p[3] = malloc(5);

if(p[0] && p[1] && p[2] && p[3]) {
strcpy(p[0], "this");
strcpy(p[1], "is");
strcpy(p[2], "a");
strcpy(p[3], "test");
}
}

(Some libraries have a strdup function which would streamline the inner malloc and strcpy calls. It's not Standard, but it's obviously trivial to implement something like it.)
Here is a code fragment which reads an entire file into memory, using the same kind of ragged array.
#include <stdio.h>
#include <stdlib.h>
extern char *agetline(FILE *);
FILE *ifp;
How can I return multiple values from a function? 
There are several ways of doing this. (These examples show hypothetical polar-to-rectangular coordinate conversion functions, which must return both an x and a y coordinate.)
1. Pass pointers to several locations which the function can fill in:
#include <math.h>

polar_to_rectangular(double rho, double theta,
double *xp, double *yp)
{
*xp = rho * cos(theta);
*yp = rho * sin(theta);
}

...
double x, y;
polar_to_rectangular(1., 3.14, &x, &y);

2. Have the function return a structure containing the desired values:

struct xycoord { double x, y; };

struct xycoord
polar_to_rectangular(double rho, double theta)
{
struct xycoord ret;
ret.x = rho * cos(theta);
ret.y = rho * sin(theta);
return ret;
}

...
struct xycoord c = polar_to_rectangular(1., 3.14);
3. Use a hybrid: have the function accept a pointer to a structure, which it fills in:

polar_to_rectangular(double rho, double theta,
struct xycoord *cp)
{
cp->x = rho * cos(theta);
cp->y = rho * sin(theta);
}

...
struct xycoord c;
polar_to_rectangular(1., 3.14, &c);

(Another example of this technique is the Unix system call stat.)

4. In a pinch, you could theoretically use global variables (though this is rarely a good idea).
Why isnt any of this standardized in C? Any real program has to do some of these things. 
Actually, some standardization has occurred along the way. In the beginning, C did not have a standard library at all; programmers always had to ``roll their own'' utility routines. After several abortive attempts, a certain set of library routines (including the str* and stdio families of routines) became a de facto standard, at least on Unix systems, but the library was not yet a formal part of the language. Vendors could (and occasionally did) provide completely different routines along with their compilers.
In ANSI/ISO Standard C, a library definition (based on the 1984 /usr/group standard, and largely compatible with the traditional Unix library) was adopted with as much standing as the language itself. The Standard C library's treatment of file and device I/O is, however, rather minimal. It states how streams of characters are written to and read from files, and it provides a few suggestions about the display behavior of control characters like b, r, and t, but beyond that it is silent. (Many of these issues are, however, addressed and standardized in Posix.)
If the Standard were to attempt to define standard mechanisms for accessing things like keyboards and displays, it might seem to be a big convenience for programmers. But it would be a monumental task: there is already a huge variety of display devices, and huge variation among the operating systems through which they are usually accessed. We cannot assume that the years to come will offer any less variety.
But I cant use all these nonstandard, system-dependent functions, because my program has to be ANSI compatible! 
You're out of luck. Either you misunderstood your requirement, or it's an impossible one to meet. ANSI/ISO Standard C simply does not define ways of doing these things; it is a language standard, not an operating system standard. An international standard which does address many of these issues is POSIX (IEEE 1003.1, ISO/IEC 9945-1), and many operating systems (not just Unix) now have POSIX-compatible programming interfaces.
It is possible, and desirable, for most of a program to be ANSI-compatible, deferring the system-dependent functionality to a few routines in a few files which are either heavily #ifdeffed or rewritten entirely for each system ported to;
What are near and far pointers? 
These days, they're pretty much obsolete; they're definitely system-specific. They had to do with 16-bit programming under MS-DOS and perhaps some early versions of Windows. If you really need to know, see a DOS- or Windows-specific programming reference. If you're using a machine which doesn't require (or permit) making the near/far pointer distinction, just delete the unnecessary ``near'' and ``far'' keywords (perhaps using the preprocessor: ``#define far /* nothing */'').
I am trying to compile this program 
I'm trying to compile this program, but the compiler is complaining that ``union REGS'' is undefined, and the linker is complaining that int86 is undefined.

Those have to do with MS-DOS interrupt programming. They don't exist on other systems.
How can I ensure that integer arithmetic doesnt overflow? 
The usual approach is to test the operands against the limits in the header file <limits.h> before doing the operation. For example, here is a ``careful'' addition function:

int
chkadd(int a, int b)
{
if(INT_MAX - b < a) {
fputs("int overflown", stderr);
return INT_MAX;
}
return a + b;
}
How can I handle floating-point exceptions gracefully? 
On many systems, you can define a function matherr which will be called when there are certain floating-point errors, such as errors in the math routines in <math.h>. You may also be able to use signal to catch SIGFPE
How can I trap or ignore keyboard interrupts like control-C? 
The basic step is to call signal, either as
#include <signal.h>
signal(SIGINT, SIG_IGN);

to ignore the interrupt signal, or as
extern void func(int);
signal(SIGINT, func);

to cause control to transfer to function func on receipt of an interrupt signal.
On a multi-tasking system such as Unix, it's best to use a slightly more involved technique:
extern void func(int);
if(signal(SIGINT, SIG_IGN) != SIG_IGN)
signal(SIGINT, func);

The test and extra call ensure that a keyboard interrupt typed in the foreground won't inadvertently interrupt a program running in the background (and it doesn't hurt to code calls to signal this way on any system).
On some systems, keyboard interrupt handling is also a function of the mode of the terminal-input subsystem; On some systems, checking for keyboard interrupts is only performed when the program is reading input, and keyboard interrupt handling may therefore depend on which input routines are being called (and whether any input routines are active at all). On MS-DOS systems, setcbrk or ctrlbrk functions may also be involved.
How can I implement a delay, or time a users response, with sub-second resolution? 
Unfortunately, there is no portable way. Routines you might look for on your system include clock, delay, ftime, gettimeofday, msleep, nap, napms, nanosleep, setitimer, sleep, Sleep, times, and usleep. (A function called wait, however, is at least under Unix not what you want.) The select and poll calls (if available) can be pressed into service to implement simple delays. On MS-DOS machines, it is possible to reprogram the system timer and timer interrupts.
Of these, only clock is part of the ANSI Standard. The difference between two calls to clock gives elapsed execution time, and may even have subsecond resolution, if CLOCKS_PER_SEC is greater than 1. However, clock gives elapsed processor time used by the current program, which on a multitasking system (or in a non-CPU-intensive program) may differ considerably from real time.
If you're trying to implement a delay and all you have available is a time-reporting function, you can implement a CPU-intensive busy-wait, but this is only an option on a single-user, single-tasking machine, as it is terribly antisocial to any other processes. Under a multitasking operating system, be sure to use a call which puts your process to sleep for the duration, such as sleep or select, or pause in conjunction with alarm or setitimer.
For really brief delays, it's tempting to use a do-nothing loop like
long int i;
for(i = 0; i < 1000000; i++)
;
How can I read in an object file and jump to locations in it? 
You want a dynamic linker or loader. It may be possible to malloc some space and read in object files, but you have to know an awful lot about object file formats, relocation, etc., and this approach can't work if code and data reside in separate address spaces or if code is otherwise privileged.
Under BSD Unix, you could use system and ld -A to do the linking for you. Many versions of SunOS and System V have the -ldl library containing routines like dlopen and dlsym which allow object files to be dynamically loaded. Under VMS, use LIB$FIND_IMAGE_SYMBOL. GNU has a package called ``dld''.
Is exit(status) truly equivalent to returning the same status from main? 
Yes and no. The Standard says that a return from the initial call to main is equivalent to calling exit. 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.)
How can I open files mentioned on the command line, and parse option flags? 
Here is a skeleton which implements a traditional Unix-style argv parse, handling option flags beginning with -, and optional filenames. (The two flags accepted by this example are -a and -b; -b takes an argument.)
#include <stdio.h>
#include <string.h>
#include <errno.h>

main(int argc, char *argv[])
{
int argi;
int aflag = 0;
char *bval = NULL;

for(argi = 1; argi < argc && argv[argi][0] == '-'; argi++) {
char *p;
for(p = &argv[argi][1]; *p != ''; p++) {
switch(*p) {
case 'a':
aflag = 1;
printf("-a seenn");
break;

case 'b':
bval = argv[++argi];
printf("-b seen ("%s")n", bval);
break;

default:
fprintf(stderr,
"unknown option -%cn", *p);
}
}
}

if(argi >= argc) {
/* no filename arguments; process stdin */
printf("processing standard inputn");
} else {
/* process filename arguments */

for(; argi < argc; argi++) {
FILE *ifp = fopen(argv[argi], "r");
if(ifp == NULL) {
fprintf(stderr, "can't open %s: %sn",
argv[argi], strerror(errno));
continue;
}

printf("processing %sn", argv[argi]);

fclose(ifp);
}
}

return 0;
}
How can a process change an environment variable in its caller? 
It may or may not be possible to do so at all. Different operating systems implement global name/value functionality similar to the Unix environment in different ways. Whether the ``environment'' can be usefully altered by a running program, and if so, how, is system-dependent.
Under Unix, a process can modify its own environment (some systems provide setenv or putenv functions for the purpose), and the modified environment is generally passed on to child processes, but it is not propagated back to the parent process. (The environment of the parent process can only be altered if the parent is explicitly set up to listen for some kind of change requests. The conventional execution of the BSD ``tset'' program in .profile and .login files effects such a scheme.) Under MS-DOS, it's possible to manipulate the master copy of the environment, but the required techniques are arcane.
How can I automatically locate a programs configuration files in the same directory as the executable? 
It's hard, in general; Even if you can figure out a workable way to do it, you might want to consider making the program's auxiliary (library) directory configurable, perhaps with an environment variable. (It's especially important to allow variable placement of a program's configuration files when the program will be used by several people, e.g. on a multiuser system.)
How can my program discover the complete pathname to the executable from which it was invoked? 
argv[0] may contain all or part of the pathname, or it may contain nothing. You may be able to duplicate the command language interpreter's search path logic to locate the executable if the name in argv[0] is present but incomplete. However, there is no guaranteed solution.
How can I invoke another program or command and trap its output? 
Unix and some other systems provide a popen function, which sets up a stdio stream on a pipe connected to the process running a command, so that the calling program can read the output (or alternatively supply the input). Using popen,
extern FILE *popen();
sprintf(cmdbuf, "sort < %s", datafile);

fp = popen(cmdbuf, "r");

/* ...now read sorted data from fp... */

pclose(fp);

(Do be sure to call pclose, as shown; leaving it out will seem to work at first but may eventually run you out of processes or file descriptors.)
If you can't use popen, you may be able to use system, with the output going to a file which you then open and read,
If you're using Unix and popen isn't sufficient, you can learn about pipe, dup, fork, and exec.
(One thing that probably would not work, by the way, would be to use freopen.)

Wednesday, March 26, 2014

राष्ट्रीय चिन्ह


विषय : राष्ट्रीय चिन्ह
प्रश्नउत्तर
राष्ट्रीय ध्वजतिरंगा
राष्ट्रीय गानजन-गन-मन
राष्ट्रीय गीतवन्दे मातरम
राष्ट्रीय चिन्हअशोक स्तम्भ
राष्ट्रीय पंचांगशक सम्वत
राष्ट्रीय वाक्यसत्यमेव जयते
राष्ट्रीयताभारतीय
राष्ट्रीय भाषाहिन्दी
राष्ट्रीय लिपिदेवनागरी
राष्ट्रीय ध्वजगीतहिन्द देश का प्यार झंडा
राष्ट्रीय नाराश्रमेव जयते
राष्ट्रपितामहात्मा गान्धी
राष्ट्रीय विदेश नीतिगुट निर्पेक्ष
राष्ट्रीय पुरस्कारभारत-रत्न
राष्ट्रीय सूचना पत्रश्वेत पत्र
राष्ट्रीय वृक्षबरगद
राष्ट्रीय मुद्रारुपया
राष्ट्रीय नदीगंगा
राष्ट्रीय पक्षीमोर
राष्ट्रीय पशुबाघ
राष्ट्रीय फूलकमल
राष्ट्रीय फलआम
राष्ट्रीय योजनापंच वर्षीय योजना
राष्ट्रीय मिठाईजलेबी
राष्ट्रीय पर्व26 जनवरी, 15 अगस्त, 2 अक्टूबर