Programing Questions

Embed Size (px)

Citation preview

  • 7/29/2019 Programing Questions

    1/43

    How can I implement opaque (abstract) data types in C?

    One good way is to use structure pointers (perhaps additionally hidden behind typedefs) which pointto structure types which are not publicly defined. In other words, a client uses structure pointers(and calls functions accepting and returning structure pointers) without knowing anything aboutwhat the fields of the structure are. (As long as the details of the structure arent needed--e.g. aslong as the -> and sizeof operators are not used--C is perfectly happy to handle pointers tostructures of incomplete type.) Only within the source files implementing the abstract data typeare complete declarations for the structures actually in scope.

    Why does the simple line-copying loop while(!feof(infp)) { fgets(buf, MAXLINE, infp); fputs(buf,outfp); } copy the last line twice?

    In C, end-of-file is only indicated after an input routine has tried to read, and failed. Usually, youshould just check the return value of the input routine:

    while(fgets(buf, MAXLINE, infp) != NULL)

    fputs(buf, outfp);

    In almost all cases, theres no need to use feof at all. (feof, or more likely ferror, may be usefulafter a stdio call has returned EOF or NULL, to distinguish between an end-of-file condition and aread error.)

    How can I recover the file name given an open stream or file descriptor?

    This problem is insoluble. Under Unix, for instance, a scan of the entire disk (perhaps involvingspecial permissions) would be required, and would fail if the descriptor were connected to a pipe orreferred to a deleted file (and could give a misleading answer

    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 string literal can be used in two different ways:

    1. As the initializer for an array of char, as in the declaration of char a[] , it specifies the initialvalues of the characters in that array (and, if necessary, its size).2. Anywhere else, it turns into an unnamed, static array of characters, and this unnamed array maybe stored in read-only memory, and which cannot be modified. In expression context, the array isconverted at once to a pointer, as usual, so the second declaration initializes p to point to the

    unnamed arrays first element.

    How do I round numbers?

    The simplest and most straightforward way is with code like

    (int)(x + 0.5)

  • 7/29/2019 Programing Questions

    2/43

    Cs floating to integer conversion truncates (discards) the fractional part, so adding 0.5 beforetruncating arranges that fractions >= 0.5 will be rounded up. For negative numbers, though, forwhich you could use something like (int)(x < 0 ? x - 0.5 : x + 0.5), or play around with the floor andceil functions.)

    You can round to a certain precision by scaling:

    (int)(x / precision + 0.5) * precision

    Handling negative numbers, or implementing even/odd rounding.

    Note that because truncation is otherwise the default, its usually a good idea to use an explicitrounding step when converting floating-point numbers to integers. Unless youre careful, its quitepossible for a number which you thought was 8.0 to be represented internally as 7.999999 and to betruncated to 7.

    How can I handle floating-point exceptions gracefully?

    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 .

    What is assert() and when would I use it?

    It is a macro, defined in , for testing `assertions. An assertion essentially documents anassumption being made by the programmer, an assumption which, if violated, would indicate aserious 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.

    What is hashing?

    Hashing is the process of mapping strings to integers, usually in a relatively small range. A `hashfunction 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.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 != \0)

    h += *str++;

    return h % NBUCKETS;

    }

  • 7/29/2019 Programing Questions

    3/43

    A somewhat better hash function is

    unsigned hash(char *str)

    {

    unsigned int h = 0;

    while(*str != \0)

    h = (256 * h + *str++) % NBUCKETS;

    return h;

    }

    which actually treats the input string as a large binary number (8 * strlen(str) bits long, assumingcharacters are 8 bits) and computes that number modulo NBUCKETS.

    What do ``lvalue and ``rvalue mean?

    An lvalue is an expression that could appear on the left-hand sign of an assignment; you can alsothink of it as denoting an object that has a location. An rvalue is any expression that has a value(and that can therefore appear on the right-hand sign of an assignment).

    Why isnt my procedure call working? The compiler seems to skip right over it. Does the codelook like this?

    myprocedure;C has only functions, and function calls always require parenthesized argument lists, even if empty.Usemyprocedure();

    Without the parentheses, the reference to the function name simply generates a pointer to thefunction, which is then discarded.

    What is C

    C is a programming language

    Why arent the sizes of the standard types precisely defined?

    Though C is considered relatively low-level as high-level languages go, it does take the position that

    the exact size of an object (i.e. in bits) is an implementation detail. (The only place where C letsyou specify a size in bits is in bit-fields within structures.) Most programs do not need precisecontrol over these sizes; many programs that do try to achieve this control would be better off ifthey didnt.Type int is supposed to represent a machines natural word size. Its the right type to use for mostinteger variables.

    I can then define these typedefs to be int, short, long, etc. depending on what machine Im

  • 7/29/2019 Programing Questions

    4/43

    using. That should solve everything, right?

    If you truly need control over exact type sizes, this is the right approach. There remain severalthings to be aware of: There might not be an exact match on some machines. (There are, for example, 36-bitmachines.) A typedef like int16 or int32 accomplishes nothing if its intended meaning is ``at least thespecified size, because types int and long are already essentially defined as being `at least 16 bitsand `at least 32 bits, respectively. Typedefs will never do anything about byte order problems (e.g. if youre trying to interchangedata or conform to externally-imposed storage layouts). You no longer have to define your own typedefs, because the Standard header contains a complete set.

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

    The new C99 Standard specifies type long long as effectively being at least 64 bits, and this typehas been implemented by a number of compilers for some time. (Others have implementedextensions such as __longlong.) On the other hand, its also appropriate to implement type short int

    as 16, int as 32, and long int as 64 bits, and some compilers do.

    Whats wrong with this declaration?char* p1, p2;I get errors when I try to use p2.

    Nothing is wrong with the declaration--except that it doesnt do what you probably want. The * in apointer declaration is not part of the base type; it is part of the declartor containing the namebeing declared. That is, in C, the syntax and interpretation of a declaration is not reallytype identifier ;but ratherbase_type thing_that_gives_base_type ;where `thing_that_gives_base_type--the declartor is either a simple identifier, or a notation like

    *p or a[10] or f() indicating that the variable being declared is a pointer to, array of, or functionreturning that base_type. (Of course, more complicated declarators are possible as well.)In the declaration as written in the question, no matter what the whitespace suggests, the basetype is char and the first declarator is ``* p1, and since the declarator contains a *, it declares p1as a pointer-to-char. The declarator for p2, however, contains nothing but p2, so p2 is declared as aplain char, probably not what was intended. To declare two pointers within the same declaration,usechar *p1, *p2;Since the * is part of the declarator, its best to use whitespace as shown; writing char* invitesmistakes and confusion.

    Im trying to declare a pointer and allocate some space for it, but its not working. Whats wrongwith this code?

    char *p;*p = malloc(10);

    The pointer you declared is p, not *p.

    Do all declarations for the same static function or variable have to include the storage classstatic?

  • 7/29/2019 Programing Questions

    5/43

    The language in the Standard does not quite require this (whats most important is that the firstdeclaration contain static), but the rules are rather intricate, and are slightly different forfunctions than for data objects. (There has also been a lot of historical variation in this area.)Therefore, its safest if static appears consistently in the definition and all declarations.

    What does extern mean in a function declaration?

    extern is significant only with data declarations. In function declarations, it can be used as astylistic hint to indicate that the functions definition is probably in another source file, but there isno formal difference betweenextern int f();andint f();

    Whats the difference between using a typedef or a #define for a user-defined type?

    In general, typedefs are preferred, in part because they can correctly encode pointer types. For

    example, consider these declarations:typedef char *String_t;#define String_d char *String_t s1, s2;String_d s3, s4;s1, s2, and s3 are all declared as char *, but s4 is declared as a char, which is probably not theintention.#defines do have the advantage that #ifdef works on them. On the other hand, typedefs have theadvantage that they obey scope rules (that is, they can be declared local to a function or block).

    Whats the difference between these two declarations?struct x1 { ... };typedef struct { ... } x2;

    The first form declares a structure tag; the second declares a typedef. The main difference is thatthe second declaration is of a slightly more abstract type--its users dont necessarily know that it isa structure, and the keyword struct is not used when declaring instances of it:x2 b;Structures declared with tags, on the other hand, must be defined with thestruct x1 a;form.(Its also possible to play it both ways:typedef struct x3 { ... } x3;Its legal, if potentially obscure, to use the same name for both the tag and the typedef, since theylive in separate namespaces.)Whats wrong with this initialization?char *p = malloc(10);My compiler is complaining about an ``invalid initializer, or something.

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

    What is the difference between these initializations?char a[] = "string literal";char *p = "string literal";

  • 7/29/2019 Programing Questions

    6/43

    My program crashes if I try to assign a new value to p[i].

    A string literal (the formal term for a double-quoted string in C source) can be used in two slightlydifferent ways:1. As the initializer for an array of char, as in the declaration of char a[] , it specifies the initialvalues of the characters in that array (and, if necessary, its size).2. Anywhere else, it turns into an unnamed, static array of characters, and this unnamed array maybe stored in read-only memory, and which therefore cannot necessarily be modified. In anexpression context, the array is converted at once to a pointer, as usual, so the second declarationinitializes p to point to the unnamed arrays first element.Some compilers have a switch controlling whether string literals are writable or not (for compilingold code), and some may have options to cause string literals to be formally treated as arrays ofconst char (for better error catching).

    Why doesntstruct x { ... };x thestruct;work?

    C is not C++. Typedef names are not automatically generated for structure tags. Either declarestructure instances using the struct keyword:struct x thestruct;or declare a typedef when you declare a structure:typedef struct { ... } x;

    x thestruct;

    Why does the declarationextern int f(struct x *p);give me an obscure warning message about ``struct x declared inside parameter list?

    In a quirk of Cs 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 sourcefile. To resolve the problem, you should probably rearrange things so that the actual declaration ofthe structure precedes the function prototype(s) using it. (Usually, both the prototype and thestructure declaration will end up in the same header file, so that the one can reference the other.)If you must mention a hitherto-unseen structure in a prototype, precede the prototype with thevacuous-looking declarationstruct x;which places an (incomplete) declaration of struct x at file scope, so that all following declarationsinvolving struct x can at least be sure theyre referring to the same struct x.

    Is there a way to compare structures automatically?

    No. There is not a good way for a compiler to implement structure comparison (i.e. to support the

    == operator for structures) which is consistent with Cs low-level flavor. A simple byte-by-bytecomparison could founder on random bits present in unused `holes in the structure (such paddingis used to keep the alignment of later fields correct. A field-by-field comparison might requireunacceptable amounts of repetitive code for large structures. Any compiler-generated comparisoncould not be expected to compare pointer fields appropriately in all cases: for example, its oftenappropriate to compare char * fields with strcmp rather than ==.If you need to compare two structures, youll have to write your own function to do so, field byfield.

  • 7/29/2019 Programing Questions

    7/43

    Whats the difference between a structure and a union, anyway?

    A union is essentially a structure in which all of the fields overlay each other; you can only use onefield at a time. The size of a union is the maximum of the sizes of its individual members, while thesize of a structure is the sum of the sizes of its members. (In both cases, the size may be increasedby padding.)

    Is there an easy way to print enumeration values symbolically?

    No. You can write a little function (one per enumeration) to map an enumeration constant to astring, either by using a switch statement or by searching an array. (For debugging purposes, a gooddebugger should automatically print enumeration constants symbolically.)

    Why doesnt this code:a[i] = i++;work?

    The subexpression i++ causes a side effect--it modifies is value--which leads to undefined behaviorsince i is also referenced elsewhere in the same expression. There is no way of knowing whether thereference will happen before or after the side effect--in fact, neither obvious interpretation mighthold. (Note that although the language in K&R suggests that the behavior of this expression isunspecified, the C Standard makes the stronger statement that it is undefined.)

    Why didprintf("%d %d", f1(), f2());call f2 first? I thought the comma operator guaranteed left-to-right evaluation.

    The comma operator does guarantee left-to-right evaluation, but the commas separating thearguments in a function call are not comma operators. The order of evaluation of the arguments toa function call is unspecified.

    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 compiler may do anything it likes when faced with undefined behavior (and, within limits, withimplementation-defined and unspecified behavior), including doing what you expect. Its unwise todepend on it, though.

    Whats the difference between ++i and i++?

    If your C book doesnt explain, get a better one. Briefly: ++i adds one to the stored value of i and

    ``returns the new, incremented value to the surrounding expression; i++ adds one to i but returnsthe prior, unincremented value.

    Why doesnt the codeint a = 1000, b = 1000;long int c = a * b;work?

  • 7/29/2019 Programing Questions

    8/43

    Under Cs integral promotion rules, the multiplication is carried out using int arithmetic, and theresult may overflow or be truncated before being promoted and assigned to the long int left-handside. Use an explicit cast on at least one of the operands to force long arithmetic:long int c = (long int)a * b;or perhapslong int c = (long int)a * (long int)b;

    (both forms are equivalent).Notice that the expression (long int)(a * b) would not have the desired effect. An explicit cast ofthis form (i.e. applied to the result of the multiplication) is equivalent to the implicit conversionwhich would occur anyway when the value is assigned to the long int left-hand side, and like theimplicit conversion, it happens too late, after the damage has been done.

    How can I ensure that integer arithmetic doesnt overflow?

    The usual approach is to test the operands against the limits in the header file beforedoing the operation. For example, here is a ``careful addition function:intchkadd(int a, int b){

    if(INT_MAX - b < a) {fputs("int overflow\n", stderr);return INT_MAX;}return a + b;}

    What are pointers really good for, anyway?

    Theyre good for lots of things, such as: dynamically-allocated arrays generic access to several similar variables (simulated) by-reference function parameters

    malloced data structures of all kinds, especially trees and linked lists walking over arrays (for example, while parsing strings) efficient, by-reference `copies of arrays and structures, especially as function parameters(Note that this is hardly a comprehensive list!)

    Does *p++ increment p, or what it points to?

    The postfix ++ and -- operators essentially have higher precedence than the prefix unary operators.Therefore, *p++ is equivalent to *(p++); it increments p, and returns the value which p pointed tobefore p was incremented. To increment the value pointed to by p, use (*p)++ (or perhaps ++*p, ifthe evaluation order of the side effect doesnt matter).

    Why cant I perform arithmetic on a void * pointer?

    The compiler doesnt know the size of the pointed-to objects. (Remember that pointer arithmetic isalways in terms of the pointed-to size.) Therefore, arithmetic on void *s is disallowed (though somecompilers allow it as an extension). Before performing arithmetic, convert the pointer either tochar * or to the pointer type youre trying to manipulate.

  • 7/29/2019 Programing Questions

    9/43

    Does C even have ``pass by reference?

    Not really.Strictly speaking, C always uses pass by value. You can simulate pass by reference yourself, bydefining functions which accept pointers and then using the & operator when calling, and thecompiler will essentially simulate it for you when you pass an array to a function.Another way of looking at it is that if an parameter has type, say, int * then an integer is beingpassed by reference and a pointer to an integer is being passed by value.Fundamentally, C has nothing truly equivalent to formal pass by reference or C++ referenceparameters. (On the other hand, function-like preprocessor macros can provide a form of ``pass byname.)

    Whats the total generic pointer type? My compiler complained when I tried to stuff functionpointers into a void *.

    There is no `total generic pointer type.void *s are only guaranteed to hold object (i.e. data) pointers; it is not portable to convert afunction pointer to type void *. (On some machines, function addresses can be very large, biggerthan any data pointers.)

    It is guaranteed, however, that all function pointers can be interconverted, as long as they areconverted back to an appropriate type before calling. Therefore, you can pick any function type(usually int (*)() or void (*)(), that is, pointer to function of unspecified arguments returning int orvoid) as a generic function pointer. When you need a place to hold object and function pointersinterchangeably, the portable solution is to use a union of a void * and a generic function pointer(of whichever type you choose

    What is this infamous null pointer, anyway?

    The language definition states that for each pointer type, there is a special value--the `nullpointer--which is distinguishable from all other pointer values and which is `guaranteed tocompare unequal to a pointer to any object or function. That is, a null pointer points definitivelynowhere; it is not the address of any object or function. The address-of operator & will never yield

    a null pointer, nor will a successful call to malloc. (malloc does return a null pointer when it fails,and this is a typical use of null pointers: as a `special pointer value with some other meaning,usually `not allocated or ``not pointing anywhere yet.)A null pointer is conceptually different from an uninitialized pointer. A null pointer is known not topoint to any object or function; an uninitialized pointer might point anywhere.

    What is NULL and how is it defined?

    As a matter of style, many programmers prefer not to have unadorned 0s scattered through theirprograms, some representing numbers and some representing pointers. Therefore, the preprocessormacro NULL is defined (by several headers, including and ) as a null pointerconstant, typically 0 or ((void *)0). A programmer who wishes to make explicit the distinctionbetween 0 the integer and 0 the null pointer constant can then use NULL whenever a null pointer is

    required.Using NULL is a stylistic convention only; the preprocessor turns NULL back into 0 which is thenrecognized by the compiler, in pointer contexts, as before. In particular, a cast may still benecessary before NULL (as before 0) in a function call argument. NULL should be used only as apointer constant.

    What does a run-time ``null pointer assignment error mean? How can I track it down?

  • 7/29/2019 Programing Questions

    10/43

    This message, which typically occurs with MS-DOS compilers, means that youve written, via a nullpointer, to an invalid location--probably offset 0 in the default data segment.A debugger may let you set some kind of data watchpoint on location 0. Alternatively, you couldwrite a bit of code to stash away a copy of 20 or so bytes from location 0, and periodically checkthat the memory at location 0 hasnt changed..

    Why cant I do something like this?extern char *getpass();char str[10];str = getpass("Enter password: ");

    Arrays are `second-class citizens in C; one upshot of this prejudice is that you cannot assign tothem. When you need to copy the contents of one array to another, you must do so explicitly. Inthe case of char arrays, the strcpy routine is usually appropriate:strcpy(str, getpass("Enter password: "));

    Practically speaking, what is the difference between arrays and pointers?

    An array is a single, preallocated chunk of contiguous elements (all of the same type), fixed in sizeand location. A pointer is a reference to any data element (of a particular type) anywhere. Apointer must be assigned to point to space allocated elsewhere, but it can be reassigned (and thespace, if derived from malloc, can be resized) at any time. A pointer can point to an array, and cansimulate (along with malloc) a dynamically allocated array, but a pointer is a much more generaldata structure.Due to the so-called equivalence of arrays and pointers, arrays and pointers often seeminterchangeable, and in particular a pointer to a block of memory assigned by malloc is frequentlytreated (and can be referenced using []) exactly as if it were a true array.

    How much memory does a pointer variable allocate?

    Thats a pretty misleading question. When you declare a pointer variable, as inchar *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 yetallocated any memory for the pointer to point to.

    I see code likechar *p = malloc(strlen(s) + 1);strcpy(p, s);Shouldnt that be malloc((strlen(s) + 1) * sizeof(char))?

    Its never necessary to multiply by sizeof(char), since sizeof(char) is, by definition, exactly 1. (Onthe other hand, multiplying by sizeof(char) doesnt hurt, and in some circumstances may help by

    introducing a size_t into the expression.)

    Why doesntstrcat(string, !);work?

    There is a very real difference between characters and strings, and strcat concatenates strings.A character constant like ! represents a single character. A string literal between double quotes

  • 7/29/2019 Programing Questions

    11/43

    usually represents multiple characters. A string literal like "!" seems to represent a single character,but it actually contains two: the ! you requested, and the \0 which terminates all strings in C.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 firstcharacter of the array. It is never correct to use one when the other is expected. To append a ! to astring, use

    strcat(string, "!");

    Whats the difference betweenconst MAXSIZE = 100;and#define MAXSIZE 100

    A preprocessor #define gives you a true compile-time constant. In C, const gives you a run-timeobject which youre not supposed to try to modify; `const really means `readonly. (But in C++,const is closer to #define.)

    Is it acceptable for one header file to #include another?

    Its 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 canmake it harder to find relevant definitions; they can lead to multiple-definition errors if a file is#included twice; they can lead to increased compilation time; and they make manual Makefilemaintenance very difficult. On the other hand, they make it possible to use header files in amodular way (a header file can #include what it needs itself, rather than requiring each #includerto 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; a clever compiler can avoidexpending any more time on later instances of an already-included header; and automated Makefilemaintenance tools (which are a virtual necessity in large projects anyway) handle dependencygeneration in the face of nested #include files easily.

    Whats the difference between #include and #include "" ?

    The syntax is typically used with Standard or system-supplied headers, while "" is typically usedfor a programs own header files.

    What are the complete rules for header file searching?

    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. Headerfiles named with "" syntax are first searched for in the `current directory, then (if not found) inthe same standard places. (This last rule, that "" files are additionally searched for as if they were files, is the only rule specified by the Standard.)Another distinction is the definition of `current directory for "" files. Traditionally (especiallyunder Unix compilers), the current directory is taken to be the directory containing the filecontaining the #include directive. Under other compilers, however, the current directory is thedirectory in which the compiler was initially invoked. (Compilers running on systems without

  • 7/29/2019 Programing Questions

    12/43

    directories or without the notion of a current directory may of course use still different rules.)It is also common for there to be a way (usually a command line option involving capital I, or maybean environment variable) to add additional directories to the list of standard places to search.Check your compiler documentation.

  • 7/29/2019 Programing Questions

    13/43

    How can inline functions help with the tradeoff of safety vs. speed?

    In straight C, you can achieve "encapsulated structs" by putting a void* in a struct, in which case thevoid* points to the real data that is unknown to users of the struct. Therefore users of the structdont know how to interpret the stuff pointed to by the void*, but the access functions cast the void*to the appropriate hidden type. This gives a form of encapsulation.

    Unfortunately it forfeits type safety, and also imposes a function call to access even trivial fields ofthe struct (if you allowed direct access to the structs fields, anyone and everyone would be able toget direct access since they would of necessity know how to interpret the stuff pointed to by thevoid*; this would make it difficult to change the underlying data structure).

    Function call overhead is small, but can add up. C++ classes allow function calls to be expandedinline. This lets you have the safety of encapsulation along with the speed of direct access.Furthermore the parameter types of these inline functions are checked by the compiler, animprovement over Cs #define macros.

    Should I explicitly call a destructor on a local variable?

    No!The destructor will get called again at the close } of the block in which the local was created. Thisis a guarantee of the language; it happens automagically; theres no way to stop it from happening.But you can get really bad results from calling a destructor on the same object a second time! Bang!Youre dead!

    When I throw this object, how many times will it be copied?

    Depends. Might be "zero."Objects that are thrown must have a publicly accessible copy-constructor. The compiler is allowedto generate code that copies the thrown object any number of times, including zero. However evenif the compiler never actually copies the thrown object, it must make sure the exception classscopy constructor exists and is accessible.

    Is there any difference between List x; and List x();?

    big difference!

    Suppose that List is the name of some class. Then function f() declares a local List object called x:

    void f(){List x; // Local object named x (of class List)...}

    But function g() declares a function called x() that returns a List:

    void g(){List x(); // Function named x (that returns a List)...}

    Is the default constructor for Fred always Fred::Fred()?

    No. A "default constructor" is a constructor that can be called with no arguments. One example of

  • 7/29/2019 Programing Questions

    14/43

    What are the 3 cases considered while deleting the nodes from the linklist?

    Case 1: CurrentNode = Head Node In this case, the node to be deleted is actually the Head node.This is a special case because there is no previous node to connect. We simply use our temp pointerto remember where Head is pointing at, advance the Head to the next position, then delete our

    saved location! Case 2: CurrentNode = End node In this case, the node to be deleted is actually theTail node. This is a special case because we have a previous node, but no node afterwards toconnect to. We save the old location of Tail using temp, set Tail equal to the previous node, set theNext pointer of Tail equal to NULL since it is at the end, then delete our temp pointer. Case 3:CurrentNode is somewhere in between In this case, there is a node before and a node after ourcurrent node. All we need to do is connect the previous node to the node after our current node. Weset temp equal to our previous node and set the Next pointer to the node after our current one(corpse). Once they are connected, we can simply delete our current pointer.

    What are the elementary functions in Linklist?

    A linked list class should contain the following elementary functions: Add To Head (Var_Typeelement) Add To Tail (Var_Type element) Var_Type Remove From Head Var_Type RemoveFrom Tail

    What is the way to point to the LinkedDeque?

    struct Node { // a node in the deque Object element; // element Node* prev; // previous nodeNode* next; // next node Node(const Object& e = Object(), Node* p = NULL, Node* n = NULL) :element(e), prev(p), next(n) { } // constructor }; typedef Node* NodePtr; // pointer to node

    What are the two methods of implementing the queues?

    Approach one : We initialize " Front = 0 " , and " Rear = -1 " ; and the test for empty queue " Front= = NextPosition(Rear) ? " . But `the main problem here is that this condition also holds for a fullqueue. Increase rear then put the value. Front points to the first element. Rear points to the lastelement. Approach two : We check " Front = = Rear ?" which indicates an empty queue. Frontpoints to a never used item, and real data starts from the next position to the front. Front mustalways points to an empty cell, and this means that well lose a place in memory (never used cell)but on the other hand its make it easier to detect an empty queue .

    What are the different ways to traverse Binary Tree?

    PREORDER: 1) Visit the root. 2) Transverse the left leaf in preorder. 3) Transverse the right leaf inpreorder. INORDER: 1) Transverse the left leaf in inorder. 2) Visit the root. 3) Transverse the rightleaf in inorder. POSTORDER: 1) Transverse the left leaf in postorder. 2) Transverse the right leaf inpostorder. 3) Visit the root.

  • 7/29/2019 Programing Questions

    15/43

  • 7/29/2019 Programing Questions

    16/43

    How do I get scrolling text in the status bar?

    This is not an HTML question, its done with a Javascript. Check any page which has this feature, andcopy the script from the source.

    These scripts have two big problems. First, usually it uses the decrement operator (c--) at somepoint. The "--" sequence in a comment actually closes it on some browsers, so your code may "leak"on those browsers. The same goes for ">".

    Second, keep in mind that many people consider this even worse than , and that it alsosuppresses the status information which normally appears there. It prevents people from knowingwhere a link goes to.

    How do I hide my source?

    You cant. The source is necessary for the browser to display your document. You have to send thecomplete, unencrypted source to the browser. Even if a particular browser doesnt have a "Viewsource" option, there are many that do, and you can always retrieve the document by hand (usingtelnet) to get its source. Or check the browsers cache.

    You can of course put a few hundred empty lines above the actual source, then newbies who dontsee the scrollbars will think there is nothing there.

    How do I get my visitors e-mail addresses?

    You cant. Although each request for a document is usually logged with the name or address of theremote host, the actual username is almost never logged as well. This is mostly because ofperformance reasons, as it would require that the server uses the ident protocol to see who is onthe other end. This takes time. And if a cache proxy is doing the request, you dont get anythingsensible.

    The most reliable way is to put up a form, asking the visitor to fill in his e-mail address. If you offer

    him something in return, he will most likely do it.

    Is there a way to get indexed better by the search engines?

    The best way is to provide good content and to avoid any tricks like repeatedly including the samekeywords, or putting keywords in white-text-on-white-background to fool search engines. And getlinks from other sites. That increases your popularity and hence your position in the search results.

    In the past you could use the META tag "keywords" to suggest extra keywords. This no longer works,because it has been heavily abused. You can however still use:

    This allows you to suggest a descriptive text that a search engine could show if this page is found ina search. You can put up to 1022 characters in the CONTENT attribute.

    How do I redirect someone to my new page?

    The most reliable way is to configure the server to send out a redirection instruction when the oldURL is requested. Then the browser will automatically get the new URL. This is the fastest way todo this. You can of course also simply put up a small page with a text like "This page has moved tohttp://new.url/, please adjust your bookmarks".

  • 7/29/2019 Programing Questions

    17/43

    What are the system requirements for windows 2003 server?Requirement s:- Minimum CPU SpeedStandard Edition 133 MHzEnterprise Edition 133 MHz for x86-based computers

    733 MHz for Itanium-based computersDatacenter Edition 400 MHz for x86-based computers733 MHz for Itanium-based computersWeb Edition 133 MHz

    Requirement Recommended CPU SpeedStandard Edition 550 MHzEnterprise Edition 733 MHzDatacenter Edition 733 MHzWeb Edition 550 MHz

    Requirement Minimum RAMStandard Edition 128 MB

    Enterprise Edition 128 MBDatacenter Edition 512 MBWeb Edition 128 MB

    Requirement Recommended Minimum RAMStandard Edition 256 MBEnterprise Edition 256 MBDatacenter Edition 1 GBWeb Edition 256 MB

    Requirement Maximum RAMStandard Edition 4 GBEnterprise Edition 32 GB for x86-based computers

    512 GB for Itanium-based computersDatacenter Edition 64 GB for x86-based computers512 GB for Itanium-based computersWeb Edition 2 GB

    Requirement Multiprocessor SupportStandard Edition Up to 4Enterprise Edition Up to 8Datacenter Edition Minimum 8 requiredMaximum 64Web Edition Up to 2

    Requirement Disk Space for SetupStandard Edition 1.5 GBEnterprise Edition 1.5 GB for x86-based computers2.0 GB for Itanium-based computersDatacenter Edition 1.5 GB for x86-based computers2.0 GB for Itanium-based computersWeb Edition 1.5 GBHow many different versions of Windows Server 2003 are there?

  • 7/29/2019 Programing Questions

    18/43

    There are six versions of Windows server 2003. they are as follows:

    1. Windows Server 2003 Web ServerThis edition supports only up to 2GB Ram and is restricted for use in a webhostingenvironment.

    2. Windows Server 2003 Standard ServerThis edition is for small and medium businesses. This edition replaced Windows 2000 Server.

    3. Windows Server 2003 Enterprise ServerThis edition is for medium and large businesses. This edition replaced Windows 2000Advanced Server.

    4. Windows Server 2003 Datacenter ServerThis edition is aimed for high end servers and supports up to 64 processors. This editionreplaced Windows 2000 Datacenter Server.

    5. Windows Server 2003 Compute Cluster EditionThis is an edition of Windows Server 2003 for clusters and supercomputers.

    6. Windows Small Business Server 2003Small Business Server 2003 is aimed for small businesses and have (license) restriction overthe other Windows Server 2003 products.Which sequences are contained in boot process?

    The boot sequence consists of the following sequences:1. Pre boot sequence2. Boot sequence3. Kernel load sequence4. Kernel initialization sequence5. Logon sequence6. Plug-and-play device detection phase

    How to activate the TELNET service?

    The service is disabled by default. You can modify start state andstart it from the Services applet, or from a console use the following:

    sc config TlntSvr start= autonet start TlntSvr

    What are the various user profiles provided by Windows 2003?

    Windows Server 2003 provides three types of user profiles:

    1. Local user profile: It is created by default when a user logs on to a system for the first time. Thelocal user profile is the default user profile, which means that if the user logs on from any othercomputer.

    2. Roaming user profile: In a roaming user profile folder is saved on the server. This ensures thatthe user profile remains consistent, and the user profile folder remains available, even when the

  • 7/29/2019 Programing Questions

    19/43

    user logs on from the different computers.

    3. Mandatory user profiles: It is like the roaming user profile, the user profile folder is saved at acentral location. In this case, if the user makes changes in the settings, the changes are not savedon the server, and the user profile remains consistent.

    What steps should be performed, if a user is unable to logon to system?

    Perform the following steps, in case you are not able to logon to a system:

    1. In many cases you might be using the wrong user name, password, or domain name. In suchcases, reset the password in Active Directory Users and Computers console.

    2. Ensure that the global catalog server is available at the time you are logging in a multiple-domainenvironment for the first time.

    3. Ensure that you have sufficient rights in the default Domain Controllers policy when you try tolog on to a domain controller.

    4. Ensure that global catalog server is available to service the request if you are attempting to logon using a UPN.

    How to verify that a computer account in windows 2003 server is disabled?

    To verify that a computer account is disabled, just check in the right pane of the Active Directoryof users and Computers window, observe that the computer account is displayed with a red Crossmark indicating that the computer account is disabled.

    What steps need to be done if the sound of system does not work and if all drivers are installed

    and the Device Manager reports it is working properly?

    In such a case, the windows audio service needs to be enabled. To enable it:

    1. Click Start, then Run, and type "services.msc" (without quotes) and click OK.2. Find the "Windows Audio" service (without quotes), right click and select Properties, select"Automatic" instead of "Disabled" (without quotes) in the startup type box3. Click Apply.4. Click Start5. Click OK.

    Why DirectX acceleration doesnt work in Windows Server 2003?

    This is by design. Graphics Acceleration is disabled by default, which disables DirectX functionality.This is to enhance server stability and is not needed in standard server scenarios. Re-enabling suchfunctionality is not a valid server testing scenario.

    What are Special Identities?

    Windows Server 2003 supports some special groups called as Special Identities. Special Identities are

  • 7/29/2019 Programing Questions

    20/43

    created and managed by Windows server 2003. As a result, system administrators cannot create ordelete special identities. In addition system administrators cannot modify the membership ofspecial identities.

    For example, Network is a special identity which includes users who are currently accessing aresource over a network.

  • 7/29/2019 Programing Questions

    21/43

    What are the technologies or tools that have been enhanced from the earlier version of SQLServer, i.e. SQL Server 2000?

    Almost all the different tools have been enhanced, some to a greater extent and some less. Thetools that have been enhanced to a greater extent are1. Database Engine2. Analysis services3. DTS4. Database administration tools5. XML Support6. ADO.NET

    What are the enhancements done to the database engine?

    The following are the new features in the database engine.1. The integration of .NET runtime in to the database has lead to the addition of new key words tothe existing set of keywords to T-SQL. These keywords mainly communicate the CLR related tasks tothe database engine.2. XML is a new datatype that could represent any xml.

    3. TRY and CATCH are the new constructs that are available with SQL Server 2005 for handling theexception conditions in T-SQL statements. This fulfills the long required need for a good mechanismto handle errors in the stored procedures.4. Now a DBA can create a Full Text catalog using the new keyword CREATE FULLTEXT CATALOG,unlike the earlier sp_fulltext catalog. In addition easier handling of the fulltext catalog by havingkeywords for attaching the detaching the catalogs.5. New relational operators such as PIVOT, UNPIVOT, and APPLY to get complex information formthe database.6. Persisted Computed columns is supported in SQL Server 2005.

    What are the enhancements in Analysis Services?

    The following are the new enhancements to the Analysis services. 1. The user interface for the

    analysis services have been drastically changed. Now there is a project based development for aspecific Business Intelligence task. The new UI features new wizard driven tasks.2. The cubes now provide customizable business metrics called Key Performance Indicators (KPI)that would assist in tracking performance leading to improved decision making abilities.3. Microsoft adds a new algorithm, which (Naive Bayes) is a classification algorithm this is quick tobuild and works well for predictive modeling.4. Object Definition Language is an XML language which allows a user to create, modify and deleteAnalysis Services Objects. This now enables a developer to perfom functions on the Analysis Serverby just sending XML messages.5. ADOMD.NET (ADO Multi Dimension) is the new standard .NET Data provider that is designed tocommunicate with multidimensional data sources.

    What are the enhancements in Data Transformation Services (DTS)?

    The new DTS designer is now integrated into the Microsoft Visual Studio Development Environment,which now provides one single integrated development experience to perform Data transformationfunctions with SQL Server 2005. This now enables and integrates with SourceSafe for versioncontrol.The new DTP engine now provides support for data flow between multiple sources, multipletransformations and multiple destinations. Now the new engine supports several newtransformations such as Multicast Transformation, Conditional Split Transformation, Sort andLookup Transformation etc.

    Long needed deployment mechanism is featured in SQL Server 2005. Now a DTS package can be

  • 7/29/2019 Programing Questions

    22/43

    What is PL/SQL and what is it used for?

    PL/SQL is Oracles Procedural Language extension to SQL. PL/SQLs language syntax, structure anddata types are similar to that of ADA. The PL/SQL language includes object oriented programmingtechniques such as encapsulation, function overloading, and information hiding (all but

    inheritance). PL/SQL is commonly used to write data-centric programs to manipulate data in anOracle database.

    Should one use PL/SQL or Java to code procedures and triggers?

    Internally the Oracle database supports two procedural languages, namely PL/SQL and Java. Thisleads to questions like "Which of the two is the best?" and "Will Oracle ever desupport PL/SQL infavour of Java?Many Oracle applications are based on PL/SQL and it would be difficult of Oracle to ever desupportPL/SQL. In fact, all indications are that PL/SQL still has a bright future ahead of it. Manyenhancements are still being made to PL/SQL. For example, Oracle 9iDB supports nativecompilation of Pl/SQL code to binaries.PL/SQL and Java appeal to different people in different job roles. The following table briefly

    describes the difference between these two language environments:PL/SQL: Data centric and tightly integrated into the database. Proprietary to Oracle and difficult to port to other database systems. Data manipulation is slightly faster in PL/SQL than in Java. Easier to use than Java (depending on your background).Java: Open standard, not proprietary to Oracle. Incurs some data conversion overhead between the Database and Java type systems. Java is more difficult to use (depending on your background).

    How can one see if somebody modified any code?

    Code for stored procedures, functions and packages is stored in the Oracle Data Dictionary. One candetect code changes by looking at the LAST_DDL_TIME column in the USER_OBJECTS dictionaryview. Example:SELECT OBJECT_NAME,TO_CHAR(CREATED, DD-Mon-RR HH24:MI) CREATE_TIME,TO_CHAR(LAST_DDL_TIME, DD-Mon-RR HH24:MI) MOD_TIME,STATUSFROM USER_OBJECTSWHERE LAST_DDL_TIME > &CHECK_FROM_DATE;

    How can one search PL/SQL code for a string/ key value?

    The following query is handy if you want to know where a certain table, field or expression isreferenced in your PL/SQL source code.

    SELECT TYPE, NAME, LINEFROM USER_SOURCEWHERE UPPER(TEXT) LIKE %&KEYWORD%;

  • 7/29/2019 Programing Questions

    23/43

    How can one keep a history of PL/SQL code changes?

    One can build a history of PL/SQL code changes by setting up an AFTER CREATE schema (ordatabase) level trigger (available from Oracle 8.1.7). This way one can easily revert to previouscode should someone make any catastrophic changes. Look at this example:

    CREATE TABLE SOURCE_HIST -- Create history tableAS SELECT SYSDATE CHANGE_DATE, USER_SOURCE.*FROM USER_SOURCE WHERE 1=2;

    CREATE OR REPLACE TRIGGER change_hist -- Store code in hist tableAFTER CREATE ON SCOTT.SCHEMA -- Change SCOTT to your schema nameDECLAREBEGINif DICTIONARY_OBJ_TYPE in (PROCEDURE, FUNCTION,PACKAGE, PACKAGE BODY, TYPE) then-- Store old code in SOURCE_HIST tableINSERT INTO SOURCE_HISTSELECT sysdate, user_source.* FROM USER_SOURCEWHERE TYPE = DICTIONARY_OBJ_TYPEAND NAME = DICTIONARY_OBJ_NAME;

    end if;EXCEPTIONWHEN OTHERS THENraise_application_error(-20000, SQLERRM);END;/show errors

    Can one print to the screen from PL/SQL?

    One can use the DBMS_OUTPUT package to write information to an output buffer. This buffer canbe displayed on the screen from SQL*Plus if you issue the SET SERVEROUTPUT ON; command.

    For example:set serveroutput onbegindbms_output.put_line(Look Ma, I can print from PL/SQL!!!);end;/

    DBMS_OUTPUT is useful for debugging PL/SQL programs. However, if you print too much, the outputbuffer will overflow. In that case, set the buffer size to a larger value, eg.: set serveroutput on size200000

    If you forget to set serveroutput on type SET SERVEROUTPUT ON once you remember, and thenEXEC NULL;. If you havent cleared the DBMS_OUTPUT buffer with the disable or enable procedure,SQL*Plus will display the entire contents of the buffer when it executes this dummy PL/SQL block.

    Note that DBMS_OUTPUT doesnt print blank or NULL lines. To overcome this problem, SETSERVEROUTPUT ON FORMAT WRAP; Look at this example with this option first disabled and thenenabled:

    SQL> SET SERVEROUTPUT ONSQL> begin2 dbms_output.put_line(The next line is blank);3 dbms_output.put_line();4 dbms_output.put_line(The above line should be blank);

  • 7/29/2019 Programing Questions

    24/43

    5 end;6 /

    The next line is blankThe above line should be blank

    SQL> SET SERVEROUTPUT ON FORMAT WRAPSQL> begin2 dbms_output.put_line(The next line is blank);3 dbms_output.put_line();4 dbms_output.put_line(The above line should be blank);5 end;6 /

    The next line is blankThe above line should be blank

    Can one call DDL statements from PL/SQL?

    One can call DDL statements like CREATE, DROP, TRUNCATE, etc. from PL/SQL by using the"EXECUTE IMMEDATE" statement. Users running Oracle versions below 8i can look at the DBMS_SQLpackage.

    beginEXECUTE IMMEDIATE CREATE TABLE X(A DATE);end;

    NOTE: The DDL statement in quotes should not be terminated with a semicolon.

    Can one use dynamic SQL statements from PL/SQL?

    Starting from Oracle8i one can use the "EXECUTE IMMEDIATE" statement to execute dynamic SQL

    and PL/SQL statements (statements created at run-time). Look at these examples. Note thatstatements are NOT terminated by semicolons:

    EXECUTE IMMEDIATE CREATE TABLE x (a NUMBER);-- Using bind variables...sql_stmt := INSERT INTO dept VALUES (:1, :2, :3);EXECUTE IMMEDIATE sql_stmt USING dept_id, dept_name, location;-- Returning a cursor...sql_stmt := SELECT * FROM emp WHERE empno = :id;EXECUTE IMMEDIATE sql_stmt INTO emp_rec USING emp_id;

    One can also use the older DBMS_SQL package (V2.1 and above) to execute dynamic statements.Look at these examples:

    CREATE OR REPLACE PROCEDURE DYNSQL AScur integer;rc integer;BEGINcur := DBMS_SQL.OPEN_CURSOR;DBMS_SQL.PARSE(cur, CREATE TABLE X (Y DATE), DBMS_SQL.NATIVE);rc := DBMS_SQL.EXECUTE(cur);DBMS_SQL.CLOSE_CURSOR(cur);END;/

  • 7/29/2019 Programing Questions

    25/43

    More complex DBMS_SQL example using bind variables:

    CREATE OR REPLACE PROCEDURE DEPARTMENTS(NO IN DEPT.DEPTNO%TYPE) ASv_cursor integer;v_dname char(20);

    v_rows integer;BEGINv_cursor := DBMS_SQL.OPEN_CURSOR;DBMS_SQL.PARSE(v_cursor, select dname from dept where deptno > :x, DBMS_SQL.V7);DBMS_SQL.BIND_VARIABLE(v_cursor, :x, no);DBMS_SQL.DEFINE_COLUMN_CHAR(v_cursor, 1, v_dname, 20);v_rows := DBMS_SQL.EXECUTE(v_cursor);loopif DBMS_SQL.FETCH_ROWS(v_cursor) = 0 thenexit;end if;DBMS_SQL.COLUMN_VALUE_CHAR(v_cursor, 1, v_dname);DBMS_OUTPUT.PUT_LINE(Deptartment name: ||v_dname);end loop;DBMS_SQL.CLOSE_CURSOR(v_cursor);

    EXCEPTIONwhen others thenDBMS_SQL.CLOSE_CURSOR(v_cursor);raise_application_error(-20000, Unknown Exception Raised: ||sqlcode|| ||sqlerrm);END;/

    What is the difference between %TYPE and %ROWTYPE?

    The %TYPE and %ROWTYPE constructs provide data independence, reduces maintenance costs, andallows programs to adapt as the database changes to meet new business needs.%ROWTYPE is used to declare a record with the same types as found in the specified databasetable, view or cursor. Example:

    DECLAREv_EmpRecord emp%ROWTYPE;

    %TYPE is used to declare a field with the same type as that of a specified tables column. Example:

    DECLAREv_EmpNo emp.empno%TYPE;

    What is the result of comparing NULL with NULL?

    NULL is neither equal to NULL, nor it is not equal to NULL. Any comparison to NULL is evaluated toNULL. Look at this code example to convince yourself.

    declarea number := NULL;b number := NULL;beginif a=b thendbms_output.put_line(True, NULL = NULL);elsif ab thendbms_output.put_line(False, NULL NULL);

  • 7/29/2019 Programing Questions

    26/43

    elsedbms_output.put_line(Undefined NULL is neither = nor to NULL);end if;end;

  • 7/29/2019 Programing Questions

    27/43

    C - A "Programming language" OR an "Intermediate language"!

    C has facilities for structured programming and allows lexical variable scope and recursion.Parameters of C functions are always passed by value. Pass-by-reference is achieved in C byexplicitly passing pointer values. C program source text is free-format, using semicolon as astatement terminator (not a delimiter).

    A simple program in C as follows:-

    #include

    int main(void){printf("hello, world\n");

    return 0;}

    C is used as an intermediate language by some higher-level languages. This is implemented in oneof two ways, as languages which:

    1. Emit C source code, and one or more other representations: machine code, object code, and/orbyte codes. Examples: some dialects of Lisp (Lush, Gambit), Squeaks C-subset Slang.

    2. Emit C source code only, and no other representation. Examples: Eiffel, Sather, Esterel, andVala.

    C source code is then input to a C compiler, which then outputs finished machine or object code.This is done to gain portability (C compilers exist for nearly all platforms) and to avoid having todevelop machine-specific code generators.

    The dimension of character string is always defined to be larger thanmaximum number of characters required to store in the array.

    When a character string is declared,the last element in acharacter array is reserved,by convention,to store the string terminator character \0.So,thedimension of character string is always defined to be larger than maximum number of charactersrequired to store in the array,so as to take care of string terminator.

    Conditional Compilation in C!

    In C, compiler can skip over a part of a source code by inserting the preprocessing commands #ifdefand #endif which have general form as:#ifdef macronamestatement1;statement2;statement3;#endifIf a macroname has been defined #ifdef then it will not get processed.

    Now, when we need to compile only a part of program. There are two cases:

    1.It often happens that a program is need to be changed at the last minute, to satisfy a client. Thisinvolves rewriting some part of source code to the clients satisfaction and delete the old code. Butthen it may happen that this code can be required by some other application. In such case, we canwrite this code in between #ifdef and #endif directives, and remove them whenever the coderequired.

  • 7/29/2019 Programing Questions

    28/43

  • 7/29/2019 Programing Questions

    29/43

    or ?

    Many C++ programmers still use instead of the newer, standard compliant library. What are the differences between the two? First, the .h notation of standard header fileswas deprecated more than five years ago. Using deprecated features in new code is never a goodidea. In terms of functionality, contains a set of templatized I/O classes which supportboth narrow and wide characters, as opposed to which only supports char-orientedstreams. Third, the C++ standard specification of iostreams interface was changed in many subtleaspects. Consequently, the interfaces and implementation of differ from those of. Finally, components are declared in namespace std whereas components are global.

    Because of these substantial differences, you cannot mix the two libraries in one program. As arule, use unless youre dealing with legacy code that is only compatible with.

    Comma-Separated Expressions

    Comma-separated expressions were inherited from C. Its likely that you use such expressions in for-

    and while-loops rather often. Yet, the language rules in this regard are far from being intuitive.First, lets see what a comma separated expression is.

    An expression may consist of one or more sub-expressions separated by commas. For example:

    if (++x, --y, cin.good ()) /*three expressions*/

    The if condition contains three expressions separated by commas. C++ ensures that each of theexpressions is evaluated and its side effects take place. However, the value of an entire comma-separated expression is only the result of the rightmost expression. Therefore, the if conditionabove evaluates as true only if cin.good () returns true. Heres another example of a commaexpression:

    int j=10;int i=0;

    while( ++i, --j){/*..repeat as long as j is not 0*/}

    Why Inheriting from a Class That Has No Virtual Destructor is Dangerous

    Classes with a non-virtual destructor arent meant to serve as base classes (such classes are usuallyknown as "concrete classes"). std::string, std::complex, and std::vector are concrete classes. Why isinheriting from such classes not recommended? When you use public inheritance, you create an is-arelationship between the base class and its derived classes. Consequently, pointers and referencesto base can actually point to a derived object. Because the destructor isnt virtual, C++ will not callthe entire destructor chain when you delete such an object. For example:

    class A{public:~A() // non virtual{// ...}};

    class B: public A /* bad; A has a non virtual dtor*/

  • 7/29/2019 Programing Questions

    30/43

  • 7/29/2019 Programing Questions

    31/43

    How is Stack implemented as a class?

    # include # include # include # define SIZE 20 classstack{ int a[SIZE]; int tos; // Top of Stack public: stack(); void push(int); int pop(); intisempty(); int isfull();}; stack::stack(){ tos=0; //Initialize Top of Stack} int stack::isempty(){return (tos==0?1:0); } int stack::isfull() { return (tos==SIZE?1:0);} void stack::push(int i)

    { if(!isfull()) { a[tos]=i; tos++; } else { cerr

  • 7/29/2019 Programing Questions

    32/43

    I want pretty graphics, not black dots for my bullet list!

    The easiest way to do it is with the definition list tags. This involves opening the list with ,surrounding each member line with the and tags, and finishing the list with the tag.

    Example:This is the first itemThis is the second itemThis is a very long line. It is to show you what happens when we get to the end of our screen. If allgoes well, the wrapped part should start directly under the first character of the line above it. Huh?It doesnt? Oh well, the price of vanity...

    Source:This is the first itemThis is the second itemThis is a very long line. It is to show you what happens when weget to the end of our screen. If all goes well, the wrapped part

    should start directly under the first character of the line aboveit. Huh? It doesnt? Oh well, the price of vanity...

    I need to set up an outline list, but I do not want to have to renumber and re-letter everythingwhen I add, delete or insert new information.

    There are going to be times when you need to present your information in outline format. Since theWeb has some academic roots, it comes already setup to do this. You may have already used theUnordered List using the tags. To do the Ordered List, you guessed it. We use the tags!

    If you look at the example below, you will see that I have taken the outline down to four levels. Theformat of this tag is very simple.

    tells the browser to start numbering with I tells the browser to start numbering with A tells the browser to start numbering with a tells the browser to start numbering with i tells the browser to start numbering with 1Each list nest or level is closed with the tag.The tricky part is remembering where you are as you nest the items of your outline. I strongly urgeyou to indent!

    Example:I. This is the first entry of the first level TYPE=IA. This would be the first of the second level TYPE=AB. This would be the second of the second level TYPE=A

    a. This would be the first of the third level TYPE=ab. This would be the second of the third level TYPE=ai. Now we are four levels deep TYPE=iii. Another one just for artistic purposes TYPE=iII. This is the second entry of the first level TYPE=IA. Now we start a new set under here. TYPE=A

    Source Code:This is the first entry of the first level TYPE=I

  • 7/29/2019 Programing Questions

    33/43

    This would be the first of the second level TYPE=AThis would be the second of the second level TYPE=AThis would be the first of the third level TYPE=aThis would be the second of the third level TYPE=a

    Now we are four levels deep TYPE=iAnother one just for artistic purposes TYPE=iThis is the second entry of the first level TYPE=INow we start a new set under here. TYPE=A

    How can I create tables with vivid colors with no spaces or lines between them?

    Source Code :

    THIS TABLE IS OUR TITLE AREA


    In this example, the black region above is one table, andthis table contains this text. By setting CELLPADDING, BORDER,and CELLSPACING all to 0 (ZERO), I can get a clean result!

    Why when I create a table with empty cells do I get what looks like a raised or miscolored cellwhere there is no data?

    As with many things in HTML, there is not what I consider to be a logical reason for this particularbehavior. The trick around it is to stick into the empty cell an invisible or non-printable character.

  • 7/29/2019 Programing Questions

    34/43

    The favorite for this purpose is

    Please look carefully at the source code . You will notice that the first table created through thefirst source code given below has a problem, and the second does not. If you get a chance, view this

    page with both Netscape and MS Internet Explorer and you will see a difference in how the browsershandle the first table!

    Source code for table with empty cell problem

    Table Containing True Empty CellsThis cell has text

    This cell has text

    Source code for table without empty cell problem

    Table with Hidden Characters in Empty Cells

    This cell has textThis cell has text

    Is there a way that I can create a link using text, but not have it underlined?

    Believe it or not, yes you can. Its strongly recommend that you consider exactly how you should useit. A reader may not realize you have created a link unless you are pretty obvious about it. Thisworks with MSIE and Netscape Communicator.

    Source code:

    I AM REALLY A LINK!________________________________________You can also turn off link underlining on an entire page

  • 7/29/2019 Programing Questions

    35/43

    by placing the following code near the top of your page,just over the and tags.

    How to Select between the SQL Server Recovery Model?

    You can select the Simple if:1) Your data is not critical.2) Losing all transactions since the last full or differential backup is not an issue.3) Data is derived from other data sources and is easily recreated.4) Data is static and does not change often.5) Space is limited to log transactions. (This may be a short-term reason, but not a good long-termreason.)

    You can select Bulk-Logged if:1) Data is critical, but logging large data loads bogs down the system.2) Most bulk operations are done off hours and do not interfere with normal transaction processing.3) You need to be able to recover to a point in time.

    You can select Full if:1) Data is critical and no data can be lost.2) You always need the ability to do a point-in-time recovery.

    3) Bulk-logged activities are intermixed with normal transaction processing.4) You are using replication and need the ability to resynchronize all databases involved inreplication to a specific point in time.

    How to implement your backup model?

    You can run backups manually,but the best approach is to schedule backups using SQL Agent. Onceyou set up the backup job, let SQL Agent run the backups on a set schedule. This can be done bythe following ways:1) Enterprise Managera) Right click on the database name.b) Select "All Tasks."c) Select "Backup Database."

    d) Once the options are set, you can then use the schedule option to create a job.

    2) T-SQLa) Using BACKUP commands, you can create the command and then use Enterprise Manager tocreate a job or use T-SQL to create the job.b) You have the ability to create Database, Differential and Transaction backups using T-SQL.

  • 7/29/2019 Programing Questions

    36/43

    Create Multiple Database Backups simultaneously

    SQL Server 2005 which allows you to create multiple backup copies of a database by a single TSQLstatement. This feature helps us to make simultaneous backups on separate devices to increasebackup reliability. Following TSQL script backup AdventureWorks database to 3 separate devices:USE master;GOBACKUP DATABASE AdventureWorksTO DISK=C:\AW1.bak Backup no. 1MIRROR TO DISK=D:\AW2.bak Backup no. 2MIRROR TO DISK=E:\AW3.bak Backup no. 3WITH FORMAT;GO

    How to implement your backup model?

    You can run backups manually,but the best approach is to schedule backups using SQL Agent. Onceyou set up the backup job, let SQL Agent run the backups on a set schedule. This can be done bythe following ways:

    1) Enterprise Managera) Right click on the database name.b) Select "All Tasks."c) Select "Backup Database."d) Once the options are set, you can then use the schedule option to create a job.

    2) T-SQLa) Using BACKUP commands, you can create the command and then use Enterprise Manager tocreate a job or use T-SQL to create the job.b) You have the ability to create Database, Differential and Transaction backups using T-SQL.

    How to change recovery models?

    There are two options that can be used to switch recovery models.

    1) Enterprise Managera) Right click on the database name, select Properties, select the Options tab and select recoverymodel from the drop-down list. Selecting OK will change the recovery model immediately.

    2) T-SQLa) ALTER DATABASE Northwind SET RECOVERY FULLb) GO

    How can you rebuild the indexes?

    As data rows are INSERTED, UPDATED and DELETED from tables, indexes get fragmented. The

    greater the fragmentation, the less effective is the index. One must ensure that the fragmentationlevel is low or non-existent. Fragmentation level can be found by executing DBCC SHOWCONTIGstatement against a particular index.

    There are three ways to remove fragmentation:1. Drop and recreate the index using CREATE INDEX WITH DROP EXISTING statement2. Execute DBCC DBREINDEX3. Execute DBCC INDEXDEFRAG

  • 7/29/2019 Programing Questions

    37/43

    DBCC DBREINDEX rebuilds a specified index or all indexes on the specified table. This statementallows indexes enforcing PRIMARY KEY and UNIQUE constraints to be rebuilt without droppingconstraints. Using DBCC DBREINDEX is easier than coding individual DROP INDEX and CREATE INDEXstatements for each index on a table.DBCC INDEXDEFRAG removes fragmentation from a specified clustered or non-clustered index.

    How to debug T-SQL stored procedures?

    I will execute -- or step into -- a sample T-SQL stored procedure and assign values to inputparameters, inspect variable contents, follow the logical flow of the procedure during runtime,evaluate T-SQL expressions, view the procedure's output, set breakpoints and generally examine thestate of the environment. (Future tips will continue along this same theme.) We will debug ourprocedure, not from Management Studio but from the Visual Studio 2005 development environment.I mention this because under SQL Server 2000 we are able to debug stored procedures using QueryAnalyzer. Perhaps debugging capabilities will be added to Management Studio in the future.

    How to tune Reporting Services?

    The following are the ways to tune Reporting Services:-

    a) Move the Reporting service and databases to a different server if needed, or expand your currentserver.b) Depending on report characteristics and application logic, it is sometimes better to have a copyof data set aside for reporting purposes. This will garner better performance in both environments.For example, if your reports are for decision support or reading static historical data, you can copythe needed data on a periodic basis and set it aside. You can also use continuous replication forreporting so as not to interfere with the OLTP environment, maybe having different indexes, datastructures, etc.c) If a copy of the data is not available, using a with (nolock) hint or a transaction isolation levelread uncommitted (dirty read) in the reports' queries can improve performance and solve lockingproblems. This can be accomplished only if the database design and application logic permit dirtyreads.

    How to Upgrade stored procedures in SQL Server 2005?

    CREATE PROCEDURE my_procedure{other parameters go here},@optionalparameter Boolean=FALSEASIf @optionalparameter=TRUE

    Begin{NEW version of stored procedure with SQL Server 2005-specific commands goes here}EndElse

    Begin{OLD version of stored procedure goes here}End

    Existing front-end calls to the stored procedure will not use the optional parameter and willexecute old code. You can test the stored procedure in place using new front-end code and thengracefully upgrade existing references to the stored procedure as you go. Since the parameter isoptional all the existing calls to the stored procedure (i.e., those without the parameter) will go

  • 7/29/2019 Programing Questions

    38/43

    through exactly as before.

    How do you restore the database in SQL Server 2005?

    To restore the database we may need to use the MOVE option to move the physical files to adifferent location and also the NORECOVERY option if we want to restore multiple backup files (i.e.full, differential and logs).

    In our output above the data files were located in the C: \Program Files\Microsoft SQLServer\MSSQL$TEST\data directory, but we now need to restore to the D: and E: drive on a differentserver. The command would look like this.

    RESTORE DATABASE NORTH

    FROM DISK = 'C:\SQL\Backup\North.bak'

    WITH MOVE 'NORTH_Data' TO 'D:\SQL\Data\North_Data.mdf',

    MOVE 'NORTH_Log' TO 'E:\SQL\Log\North_Log.ldf'

    How to restore the database with full, differential and log files?

    Following is the command used to restore and move both a full, differential and log backups:-

    RESTORE DATABASE NORTHFROM DISK = 'C:\SQL\Backup\North.bak'WITH NORECOVERY,MOVE 'NORTH_Data' TO 'D:\SQL\Data\North_Data.mdf',MOVE 'NORTH_Log' TO 'E:\SQL\Log\North_Log.ldf'

    RESTORE DATABASE NORTHFROM DISK = 'C:\SQL\Backup\North_Diff.bak'

    WITH NORECOVERY,MOVE 'NORTH_Data' TO 'D:\SQL\Data\North_Data.mdf',MOVE 'NORTH_Log' TO 'E:\SQL\Log\North_Log.ldf'

    RESTORE LOG NORTHFROM DISK = 'C:\SQL\Backup\North_Log.bak'WITH RECOVERY,MOVE 'NORTH_Data' TO 'D:\SQL\Data\North_Data.mdf',MOVE 'NORTH_Log' TO 'E:\SQL\Log\North_Log.ldf'

    Please check and let me know if any modifications are required.

    How to report on space utilization in data and log files?

    You can expand or shrink a data file or a transaction log file, possibly when using the DBCCSHRINKDATABASE or DBCC SHRINKFILE command.

    The sysindexes table can become inaccurate over time, especially in databases that grow frequentlyand/or shrink frequently. The DBCC UPDATEUSAGE command reports and corrects inaccuracies inthe sysindexes table. You should execute this statement if you expect your database or table size to

  • 7/29/2019 Programing Questions

    39/43

    be different than what is reported by sp_spaceused system procedure.

    You must execute DBCC UPDATEUSAGE after each time you shrink database files with DBCCSHRINKDATABASE or DBCC SHRINKFILE, or as a regularly scheduled maintenance task.

  • 7/29/2019 Programing Questions

    40/43

    Rewrite complex subqueries with temporary tables

    Oracle created the global temporary table (GTT) and the SQL WITH operator to help divide-and-conquer complex SQL sub-queries (especially those with WHERE clause subqueries, SELECT clausescalar subqueries and FROM clause in-line views). Tuning SQL with temporary tables (andmaterializations in the WITH clause) can result in amazing performance improvements.

    Use minus instead of EXISTS subqueries

    Some say that using the minus operator instead of NOT IN and NOT Exists will result in a fasterexecution plan.

    Use SQL analytic functions

    The Oracle analytic functions can do multiple aggregations (e.g. rollup by cube) with a single passthrough the tables, making them very fast for reporting SQL.

    Re-write NOT EXISTS and NOT EXISTS subqueries as outer joins

    In many cases of NOT queries (but ONLY where a column is defined as NULL), you can re-write theuncorrelated subqueries into outer joins with IS NULL tests. Note that this is a non-correlated sub-query, but it could be re-written as an outer join.

    select book_key from bookwherebook_key NOT IN (select book_key from sales);

    Below we combine the outer join with a NULL test in the WHERE clause without using a sub-query,giving a faster execution plan.

    select b.book_key from book b, sales swhereb.book_key = s.book_key(+)ands.book_key IS NULL;

    Index your NULL values

    If you have SQL that frequently tests for NULL, consider creating an index on NULL values. To getaround the optimization of SQL queries that choose NULL column values (i.e. where emp_name ISNULL), we can create a function-based index using the null value built-in SQL function to index onlyon the NULL columns.

    Leave column names alone

    Never do a calculation on an indexed column unless you have a matching function-based index(a.k.a. FBI). Better yet, re-design the schema so that common where clause predicates do not needtransformation with a BIF:

    where salary*5 > :myvaluewhere substr(ssn,7,4) = "1234"

  • 7/29/2019 Programing Questions

    41/43

  • 7/29/2019 Programing Questions

    42/43

    C - A "Programming language" OR an "Intermediate language"!

    C has facilities for structured programming and allows lexical variable scope and recursion.Parameters of C functions are always passed by value. Pass-by-reference is achieved in C byexplicitly passing pointer values. C program source text is free-format, using semicolon as astatement terminator (not a delimiter).

    A simple program in C as follows:-

    #include

    int main(void){printf("hello, world\n");

    return 0;}

    C is used as an intermediate language by some higher-level languages. This is implemented in oneof two ways, as languages which:

    1. Emit C source code, and one or more other representations: machine code, object code, and/orbyte codes. Examples: some dialects of Lisp (Lush, Gambit), Squeaks C-subset Slang.

    2. Emit C source code only, and no other representation. Examples: Eiffel, Sather, Esterel, andVala.

    C source code is then input to a C compiler, which then outputs finished machine or object code.This is done to gain portability (C compilers exist for nearly all platforms) and to avoid having todevelop machine-specific code generators.

    The dimension of character string is always defined to be larger thanmaximum number of characters required to store in the array.

    When a character string is declared,the last element in acharacter array is reserved,by convention,to store the string terminator character \0.So,thedimension of character string is always defined to be larger than maximum number of charactersrequired to store in the array,so as to take care of string terminator.

    Conditional Compilation in C!

    In C, compiler can skip over a part of a source code by inserting the preprocessing commands #ifdefand #endif which have general form as:#ifdef macronamestatement1;statement2;statement3;#endifIf a macroname has been defined #ifdef then it will not get processed.

    Now, when we need to compile only a part of program. There are two cases:

    1.It often happens that a program is need to be changed at the last minute, to satisfy a client. Thisinvolves rewriting some part of source code to the clients satisfaction and delete the old code. Butthen it may happen that this code can be required by some other application. In such case, we canwrite this code in between #ifdef and #endif directives, and remove them whenever the coderequired.

  • 7/29/2019 Programing Questions

    43/43