Вы находитесь на странице: 1из 26

NOTE: We have stopped this service and mock interviews will no longer be active

interviewstreetalpha

Sign In or Sign up
Home Articles Pricing Online Test

Search

Articles Podcasts Preparation Kit Latest News

Subscribe in a reader

Subscribe by e-mail

Related Articles

Main function in C program - is it necessary? Top 5 Interview Questions on Chess Binary Search - how does it work?

Article How does a C program work?

This article describes the various stages your C code or program goes through before producing the desired output. Stage 1 : Writing your code or program and saving it with ".c" extension . Stage 2: Now you need to compile your program. In simple terms it's job is to check whether your code follows all the rules of the C language (i.e) errors related to syntax, declarations are not present and convert the code into a language which is understood by your computer. Let us now explore the compilation process in a bit more detail: The aim of compiler is to produce a Relocatable Object Module, commonly known as an object file, with extension ".o". For a C program, relocatable object module has has three logical blocks of addresses:

A Text Segement (also known a Code Segment) , which

contains a block of machine instructions.


Data Segment which is a block of static variables. Stack Segment which represents the stack which is used

while the program is in execution . Now the relocatable object module contains the relative addresses of the various code segments. For example if you have used a user defined function "foo()" , which is also present in the same file, then it will contain its relative entry address. However , for funtions like "printf()" or any other function, whose definition is not present in the code that you have written, the compiler can't get their relative addresses at the compile time. It annotates each such reference to an external address, so that the linker can place the correct address at the link time. Stage 3: Link time: At link time the code and data segments of each relocatable

object module are combined to form the absolute module or the load module . Linker combines all the data segments into a single data segment and all code segments into a single code segment. When data segments are combined, the relative addresses of individual static variables are changed. The linker then relocates the addresses in the instructions so that they refer the addresses in the aggregated data segment. All the undefined addresses references are found by linkage editor as it combines the relocatable module: the resulting composition includes all the program text and data, so that every reference to the data or program entry point is resolved.The absolute program is stored in a file(in the secondary memory) until a process is ready to use it.

Image Courtesy: "Basic Memory Management",from the book Operating Systems, Third Edition by Gary Nutt

Stage 4: Load time: Now when a process is allocated to use the absolute module, the memory manager allocates a block of primary memory to the process. Then the loader copies the absolute program and data into the newly allocated memory. The interseting part is, till now all the addresses in the absolute program file were relative, starting from 0, but now the program is at some particular physical address in the primary memory, so loader translates all internal logical primary memory addresses, with zero being replaced by the physical memory address, and other addresses changed according to it. At this stage the program is called executable program, the one

expected by the hardware control unit, just before it is added to the primary memory at the proper location. The PC (program counter) is set to the primary memory address of the first executable instruction (i.e.) main entry point for the program. Now the program is ready to run, the static and dynamic binding concepts also play an important role, but beyond the scope of this article. Whenever we write a piece of C code we do it in an environment known as execution environment. According to C standards the execution environment includes the characteristics of the processor that will execute the program image (instruction set, number of registers, memory access characteristics, etc.), and the runtime interface to the host environment (storage allocation, function calling conventions, etc.). In C there are basically two types of execution environments

Hosted environment Freestanding environment

Hosted Environment:
Hosted environment is one which a normal developer encounters everyday while coding. It already provides inbuilt support to most of the standard libraries and functions. In a hosted environment the developer does not need to worry about the basic functionality required - eg I/O functionality provided by "stdio.h" . GCC is one such platform which provides a hosted environment which may itself be running on any OS like Linux. And also starting point of any hosted environment is the "main function". There are different implementations present to execute a program image. These usually involve executing before main some is internal, Then implementation-specific function, called.

association between this internal function and main is usually made at link-time by having the internal function make a call to "main function", which is resolved by the linker in the same way as other function calls.

To sum-up a hosted environment provides a lot of standard library functions which may or may not be needed by developer but are provided by default.

Freestanding Environment:
Freestanding environment on the other hand is intended to interact directly with the hardware. A freestanding environment does not require any built-in library functions. A freestanding implementation is one in which execution may take place without the benefit of an operating system, and has an implementation-defined set of libraries that include certain language-support libraries.

Why no "main function" in Linux kernel source code?


In a free standing environment there is no standard place to begin the execution of the code. In many cases there is no named program at all. Switching on, or resetting, the freestanding host causes the processor instruction pointer to be set to some predefined location in memory, and execution continues with the subsequent instructions. Traditionally there is a small bootstrap loader at this location, which copies a larger program from a storage device into memory and jumps to the start of that program (it might be a simple operating system). In other cases that storage device is ROM and the program will already be in memory at the predefined location. Translated program instructions are executed directly from the storage device. Once switched on, the host may have buttons that cause the processor to be reset to a different location, causing different functions to be invoked on startup. For example OS kernel which itself is supposed to provide an hosting environment for writing C code is written according to freestanding environment in mind, this is the reason there is no "main function" in Linux kernel source code . Generally in the case of Linux the function placed at the default boot-up address is start_kernel(). In most of these cases the code on freestanding environment is used by developers who cannot afford to have all the unnecessary libraries or does not require them like the Embedded System developers .

However there are some libraries which are needed by both hosted and freestanding environment . They are listed below: "float.h" "stdint.h" These libraries fulfil basic needs of C programming and come as a part of standard libraries. References:

"limits.h"

"stdarg.h"

"stddef.h"

"iso646.h"

"The New C Standard" by Derek M. Jones "Standards and specs: The nitty-gritty on the C committee in

IBM Technical Library


What is a function in C? What is the need of using functions?

A function is a block of code that has a name and is reusable i.e. it can be executed from as many different points in a C Program as required. We can divide a long C program into small blocks which can perform a certain task. Using functions, 1)we can make the code much more readable 2)remove repeated coding. For example, consider the following code. int convertHHMMSS_To_Seconds(int hours, int mins, int seconds) { int totalSeconds = 0; totalSeconds = hours*60*60 + mins*60 + seconds; return totalSeconds; } We can use the above function as many times as we want without repeating the code inside the function. Another advantage of using functions is that, if we need to change the code after sometime, we need to make the edit at only one place.

What is the difference between malloc and calloc?

The differences between malloc and calloc are as follows, (i). Malloc allocate bytes of memory, whereas calloc allocates block of memory. (ii). Malloc allocates memory as a single contiguous block, whereas calloc allocates memory which may/may not be contiguous. (iii). If a single contiguous block cannot be allocated then malloc would fail, whereas using calloc if memory

is allocated in non-contiguous blocks when a single contiguous block cannot be allocated. (iv). The values stored in the allocated memory space by calloc is zero by default, whereas with malloc the allocated memory could have any value. (v). Malloc requires one argument - the number of bytes you want to allocate dynamically. Calloc requires two arguments. The first is the number of variables you'd like to allocate memory for. The second is the size of each variable. How can you swap two variables without using a third variable?

Method One : (Using arithmetic operators) int a = 10, b = 20; a = a + b; b = a - b; a = a - b; Method Two : (Using bitwise operators) int a = 10, b = 20; a = a ^ b; b = a ^ b; a = a ^ b; What is recursion? Give an example for recursion.

Recursion is a technique involving in which a function calls itself and has a termination condition so that successive repetitions are processed up to the critical step where the condition is met at which time the rest of each repetition is processed from the last one called to the first. One simple example is the idea of building a wall that is ten feet high; if I want to build a ten foot high wall, then I will first build a 9 foot high wall, and then add an extra foot of bricks. Conceptually, this is like saying the "build wall" function takes a height and if that height is greater than one, first calls itself to build a lower wall, and then adds one a foot of bricks. The most common example for recursion is the find the factorial of a number long long int factorial(int n) { if (n <= 1) return 1; else return (n * factorial(n-1)); } Given the following program, remove all if else and replace it with

switch case if (a == 10) { b = 20; } else if (a == 50) { b = 25; } else if (a == 40) { b = 160; } else { b = 16; } switch(a) { case 10: b=20; case 50: b=25; case 40: b=60; default: b=16; }

What is a linked list?

A linked list is a data structure that consists of a sequence of data records such that in each record there is a field that contains a reference (i.e., a link) to the next record in the sequence. The chain of records are called nodes. Each node has at least two members, one of which points to the next item or node in the list. These are defined as Single Linked Lists because they only point to the next item, and not the previous. Those that do point to both are called Doubly Linked Lists. What is Virtual Memory?

Virtual memory is a computer system technique which gives an application program the impression that it has contiguous working memory (an address

space), while in fact it may be physically fragmented and may even overflow on to disk storage. In other words, it is an imaginary memory area supported by some operating systems. You can think of virtual memory as an alternate set of memory addresses. Programs use these virtual addresses rather than real addresses to store instructions and data. When the program is actually executed, the virtual addresses are converted into real memory addresses. The purpose of virtual memory is to enlarge the address space, the set of addresses a program can utilize. For example, virtual memory might contain twice as many addresses as main memory. A program using all of virtual memory, therefore, would not be able to fit in main memory all at once. Nevertheless, the computer could execute such a program by copying into main memory those portions of the program needed at any given point during execution. Checkout memory. What is DDL and DML? What is the difference DDL and DML? http://en.wikipedia.org/wiki/Virtual_memory and

http://www.howstuffworks.com/virtual-memory.htm to know more about virtual

Data Definition Language (DDL) statements are used to define the database structure or schema. Data Manipulation Language (DML) statements are used for managing data within schema objects. Examples of DDL are CREATE (create objects in the database), ALTER (alters the structure of the database), DROP (delete objects from the database), RENAME (rename an object) etc. Examples of DML are SELECT (retrieve data from the a database), INSERT (insert data into a table), UPDATE (updates existing data within a table), DELETE (deletes records from a table) etc. DML commands can usually be rolled back (if the database supports rollback), but DDL commands can not be rolled back. What is the differece between TRUNCATE and DROP query?

TRUNCATE removes all rows from a table. The DROP command removes a table from the database. All the tables' rows, indexes and privileges will also be removed. If a table is dropped, all the relationships with other tables will no longer be valid, the integrity constraints will be dropped, grant or access privileges on the table will also be dropped, if want use the table again it has to be recreated with the integrity constraints, access privileges and the relationships with other tables should be established again. But, if a table is truncated, the table structure remains the same, therefore any of the above problems will not exist. What is the difference between VIEW and TABLE?

A table is where you store your data. The table actually occupies space on disk. A view is a stored query. A view is different from a regular table in that it does not store data, but executes a stored SELECT statement each time it is accessed. Views are used primarily to store a common query in the database. Without the view, you might have the same complex query stored in multiple locations in your application code. If you need to make a change, you would have to change the query in all locations. However, if that query were in a view, you would only have to change it in one location. The other common reason for a view is for security purposes. Write a query to extract only the duplicate records from the table?

Let us assume a table called users, which has a column named email_address SELECT `email_address` FROM `users` GROUP BY (`email_address`) HAVING ( COUNT(`email_address`) > 1 ) What is the difference between a primary key and a foreign key?

A primary key is an attribute (or combination of attributes) that uniquely identifies each row in a relation. The primary key of an entity set allows us to distinguish among the various entities of the set. A foreign key is an attribute in a relation of database that serves as the primary key of another relation in the same database. Primary keys enforce entity integrity by uniquely identifying entity instances. Foreign keys enforce referential integrity by completing an association between two entities. Primary key is a unique key but foriegn key usually refers to primary key. Explain function overloading and function overriding.

Function overloading is the process of defining the same function name with different arguments,number of arguments ,or ordinal positions of arguments. Function overriding is the process of defining the Base class function in the derived class with different code implementation. Example for function overloading. int area(int side); int area(int length, int breadth); int area(int length, int breadth, int height); Example for function overriding.

class Parent { virtual int area(int side){ return side*side;} } class Child : public Parent { int area(int side){ return side*side+20; } } What is a complete binary tree?

A complete binary tree is a binary tree in which every level, except possibly the deepest, is completely filled. At depth n, the height of the tree, all nodes must be as far left as possible. In other words, a complete binary tree is a special case of a binary tree, in which all the levels, except perhaps the last, are full; while on the last level, any missing nodes are to the right of all the nodes that are present. What is a binary search tree? Why is searching easier in a binary

search tree? A binary search tree is a binary tree with the following properties, (i) The left subtree of a node contains only nodes with keys less than the node's key. (ii) The right subtree of a node contains only nodes with keys greater than the node's key. (iii) Both the left and right subtrees must also be binary search trees. The most common operations performed on a binary search tree is searching for a key stored in the tree. These operations run in O(h) time where h is the height of the tree i.e., h is the number of links root node to the deepest node. 1. What is virtual constructors/destructors? Virtual destructors: If an object (with a non-virtual destructor) is destroyed explicitly by applying the delete operator to a base-class pointer to the object, the base-class destructor function (matching the pointer type) is called on the object. There is a simple solution to this problem declare a virtual base-class destructor. This makes all derivedclass destructors virtual even though they dont have the same name as the base-class destructor. Now, if the object in the hierarchy is destroyed explicitly by applying the delete operator to a base-class pointer to a derived-class object, the destructor for the appropriate class is called. Virtual constructor: Constructors cannot be virtual. Declaring a constructor as a virtual function is a syntax error. Does c++ support multilevel and multiple inheritance? Yes. 2. Why Garbage collection? Since C++ does not provide automatic garbage collection like some other languages, smart pointers can be used for that purpose. The simplest garbage collection scheme is reference counting or reference linking, but it is quite possible to implement more sophisticated garbage collection schemes with smart pointers.

3. How to write a swap( ) function which swaps the values of the variables using bitwise operators.? Ans: Here is the swap( ) function. swap ( int *x, int *y ) { *x ^= *y ; *y ^= *x ; *x ^= *y ; } The swap( ) function uses the bitwise XOR operator and does not require any temporary variable for swapping. 4. What are the advantages of inheritance? It permits code reusability. Reusability saves time in program development. It encourages the reuse of proven and debugged high-quality software, thus reducing problem after a system becomes functional. 5. What is the difference between declaration and definition? The declaration tells the compiler that at some later point we plan to present the definition of this declaration. E.g.: void stars () //function declaration The definition contains the actual implementation. E.g.: void stars () // declarator { for(int j=10; j>=0; j--) //function body cout<<*; cout< function_declaration; template function_declaration; The only difference between both prototypes is the use of keyword class or typename, its use is indistinct since both expressions have exactly the same meaning and behave exactly the same way. 6. What do you mean by inline function? The idea behind inline functions is to insert the code of a called function at the point where the function is called. If done carefully, this can improve the application's performance in exchange for increased compile time and possibly (but not always) an increase in the size of the generated binary executables. 7. What is virtual class and friend class? Friend classes are used when two or more classes are designed to work together and need access to each other's implementation in ways that the rest of the world shouldn't be allowed to have. In other words, they help keep private things private. For instance, it may be desirable for class DatabaseCursor to have more privilege to the internals of class Database than main() has. 8. What is function overloading and operator overloading? Student Resources Function overloading: C++ enables several functions of the same name to be defined, as long as these functions have different sets of parameters (at least as far as their types are concerned). This capability is called function overloading. When an overloaded function is called, the C++ compiler selects the proper function by examining the number, types and order of the arguments in the call. Function overloading is commonly used to create several functions of the same name that perform similar tasks but on different data types. Operator overloading allows existing C++ operators to be redefined so that they work on objects of user-defined classes. Overloaded operators are syntactic sugar for equivalent function calls. They form a pleasant facade that doesn't add anything fundamental to the language (but they can improve understandability and reduce maintenance costs). 9. Difference between realloc() and free()?

The free subroutine frees a block of memory previously allocated by the malloc subroutine. Undefined results occur if the Pointer parameter is not a valid pointer. If the Pointer parameter is a null value, no action will occur. The realloc subroutine changes the size of the block of memory pointed to by the Pointer parameter to the number of bytes specified by the Size parameter and returns a new pointer to the block. The pointer specified by the Pointer parameter must have been created with the malloc, calloc, or realloc subroutines and not been deallocated with the free or realloc subroutines. Undefined results occur if the Pointer parameter is not a valid pointer 10. What do you mean by binding of data and functions? Encapsulation. 11. What is abstraction? Abstraction is of the process of hiding unwanted details from the user. 12. What is encapsulation? Packaging an objects variables within its methods is called encapsulation. 13. What is the difference between an object and a class? Classes and objects are separate but related concepts. Every object belongs to a class and every class contains one or more related objects. A Class is static. All of the attributes of a class are fixed before, during, and after the execution of a program. The attributes of a class don't change. The class to which an object belongs is also (usually) static. If a particular object belongs to a certain class at the time that it is created then it almost certainly will still belong to that class right up until the time that it is destroyed. An Object on the other hand has a limited lifespan. Objects are created and eventually destroyed. Also during that lifetime, the attributes of the object may undergo significant change. 14. What is polymorphism? Explain with an example? "Poly" means "many" and "morph" means "form". Polymorphism is the ability of an object (or reference) to assume (be replaced by) or become many different forms of object. Example: function overloading, function overriding, virtual functions. Another example can be a plus + sign, used for adding two integers or for using it to concatenate two strings. 15. What do you mean by inheritance? Inheritance is the process of creating new classes, called derived classes, from existing classes or base classes. The derived class inherits all the capabilities of the base class, but can add embellishments and refinements of its own. 16. What is a scope resolution operator? A scope resolution operator (::), can be used to define the member functions of a class outside the class. 17. What are virtual functions? A virtual function allows derived classes to replace the implementation provided by the base class. The compiler makes sure the replacement is always called whenever the object in question is actually of the derived class, even if the object is accessed by a base pointer rather than a derived pointer. This allows algorithms in the base class to be replaced in the derived class, even if users don't know about the derived class. 18. What is friend function? As the name suggests, the function acts as a friend to a class. As a friend of a class, it can access its private and protected members. A friend function is not a member of the class. But it must be listed in the class definition. 19. What is the difference between class and structure? Structure: Initially (in C) a structure was used to bundle different type of data types together to perform a particular functionality. But C++ extended the structure to contain functions also. The major difference is that all declarations inside a structure are by default public. Class: Class is a successor of Structure. By default all the members inside the class are private.

20. What is public, protected, private? Public, protected and private are three access specifiers in C++. Public data members and member functions are accessible outside the class. Protected data members and member functions are only available to derived classes. Private data members and member functions cant be accessed outside the class. However there is an exception can be using friend classes. 21. What is an object? Object is a software bundle of variables and related methods. Objects have state and behavior. 22. What is a class? Class is a user-defined data type in C++. It can be created to solve a particular kind of problem. After creation the user need not know the specifics of the working of a class. Q. When linking C or Assembly language modules with C++ modules I get undefined symbol errors at link time. It appears that none of the C or Assembly public symbols can be found. A. C++ is a strongly typed language. In order to support the language to its fullest, Turbo C++ must attach information to the symbols generated for function names and variables. When this is done, the symbol will no longer match the standard C style function name. In order to link correctly, the compiler must be notified that the symbol is declared in an external module without type information tacked on to the symbol. This is done by prototyping the function as type extern "C". Here is a quick example: extern "C" int normal_c_func( float, int, char ); // name not altered void cplusplus_function( int ); // name altered See related comments under Linker Errors and in the Paradox Engine question in this section. Q. Classes with static data members are getting linker errors ("undefined"). A. This code is built into Turbo C++ 1.0 but not in version 3.0. In the 1.0 compiler, static members without definitions were given a default value of 0. This default definition will no longer be made in the compiler. The programmer must now give an explicit definition for each static member. Here is a quick example: class A { static int i; }; A linker error saying that A::i is not defined will result unless the source also contains a line such as: int A::i = 1; Q. What potential problems can arise from typecasting a base class pointer into a derived class pointer so that the derived class's member functions can be called? A. Syntactically this is allowable. There is always the possibility of a base pointer actually pointing to a base class. If this is typecast to a derived type, the method being called may not exist in the base class. Therefore, you would be grabbing the address of a function that does not exist. Q: What's the difference between the keywords STRUCT and CLASS? A: The members of a STRUCT are PUBLIC by default, while in CLASS, they default to PRIVATE. They are otherwise functionally equivalent. Q: I have declared a derived class from a base class, but I can't access any of the base class members with the derived class function. A: Derived classes DO NOT get access to private members of a base class. In order to access members of a base class, the base class members must be declared as either public or protected. If they are public, then any portion of the program can access them. If they are protected, they are accessible by the class members, friends, and any derived classes. Q: How can I use the Paradox Engine 1.0 with C++?, A: Because the Paradox Engine functions are all compiled as C functions, you will have to assure that the names of the functions do not get "mangled" by the C++ compiler. To do this you need to prototype the Engine functions as extern "C". In the pxengine.h header file insert the following code at the lines indicated.

/* inserted at line # 268 */ #ifdef __cplusplus extern "C" { #endif /* inserted at line # 732, just before the final #endif */ #ifdef __cplusplus } #endif Paradox Engine version 2.0 is "aware" of C++ and thus does not require any modifications to its header file. Q: I have a class that is derived from three base classes. Can I insure that one base class constructor will be called before all other constructors? A: If you declare the base class as a virtual base class, its constructor will be called before any non-virtual base class constructors. Otherwise the constructors are called in left-to-right order on the declaration line for the class. Q: Are the standard library I/O functions still available for use with the C++ iostreams library? A: Yes, using #include functions such as printf() and scanf() will continue to be available. However, using them in conjunction with stream oriented functions can lead to unpredictable behaviour. Q. In C++, given two variables of the same name, one local and one global, how do I access the global instance within the local scope? A. Use the scope (::) operator. int x = 10; for(int x=0; x < ::x; x++) { cout << "Loop # " << x << "\n"; // This will loop 10 times } Q. Will the following two functions be overloaded by the compiler, or will the compiler flag it as an error? Why? void test( int x, double y); & int test( int a, double b); A. The compiler will flag this as a redeclaration error because neither return types nor argument names are considered when determining unique signatures for overloading functions. Only number and type of arguments are considered. Q. If I pass a character to a function which only accepts an int, what will the compiler do? Will it flag it as an error? A. No. The compiler will promote the char to an int and use the integer representation in the function instead of the character itself. Q. I was trying to allocate an array of function pointers using the new operator but I keep getting declaration syntax errors using the following syntax: new int(*[10])(); What's wrong? A. The new operator is a unary operator and binds first to the int keyword producing the following: (new int) (*[10])(); You need to put parentheses around the expression to produce the expected results: new (int (*[10]()); Q. What are inline functions? What are their advantages? How are they declared?

A. An inline function is a function which gets textually inserted by the compiler, much like macros. The advantage is that execution time is shortened because linker overhead is minimized. They are declared by using the inline keyword when the function is declared: inline void func(void) { cout << "printing inline function \n"; } or by including the function declaration and code body within a class: class test { tv public: void func(void) { cout << "inline function within a class.\n"} }; Q. If I don't specify either public or private sections in a class, what is the default? A. In a class, all members are private by default if neither public nor private sections are declared. Q. What does the _seg modifier do? A. Using _seg causes a pointer to become a storage place for a segment value, rather than an offset ( or a segment/offset ). For instance, if "int _seg *x" contains the value 0x40, then when you use "*x", the value pointed to will be at segment 0x40, offset 0. If you add a value to the pointer, the value is multiplied by the size of the pointer type. That new value is used as an offset, and is combined with the segment value contained in the pointer. For instance, int _seg *x; int value; x = (int _seg *)0x40; value = *(x + 20); value is assigned the value of the integer at 0x40:0x28 (Remember, 20 * sizeof(int) = 40 = 0x28). Q. Can I statically allocate more than 64K of data in a single module? A. Yes. Far data items are now supported: ... char far array1[60000L]; char far array2[60000L]; ... For arrays larger than 64k use: char huge array3[100000L]; Q. What is a friend member function? A. Declaring a friend gives non-members of a class access to the non-public members of a class. Q. Why do I get a "Type name expected" error on my definition of a friend class in my new class? A You need to let the compiler know that the label you use for your friend class is another class. If you do not want to define your entire class, you can simply have "class xxx", where xxx is your label. Q: How can I output hex values in upper case using the iostream libraries? A: You need to set the state of the stream using setf(). For example, #include int main(void)

{ cout << hex; cout << "\nNot upper-case : " << 255; cout.setf(ios::upper-case); cout << "\nUppercase : " << 255; return 0; } Q. What is the "this" pointer? A. "this" is a local variable in the body of a non-static member function. It is a pointer to the object for which the function was invoked. It cannot be used outside of a class member function body. Q. Why does a binary member function only accept a single argument? A. The first argument is defined implicitly. Q. Looking through the class libraries there are definitions in classes which look like: class test { int funct( void ) const; }; What is the const keyword doing here? A. There is a pointer to the object for which a function is called known as the 'this' pointer. By default the type of 'this' is X *const ( a constant pointer). The const keyword changes the type to const X *const ( a constant pointer to constant data ). Q: I want to use _new_handler and set_new_handler. A: Turbo C++ supports _new_handler and set_new_handler. The type of _new_handler is as follows. typedef void (*vfp)(void); vfp _new_handler; vfp set_new_handler( vfp ); Q: I would like to use C++ fstreams on a file opened in binary mode, how is this done? A: Use ios::binary as the open mode for the file: #include ifstream binfile; binfile.open("myfile.bin", ios::binary); Q: How can I get at the DOS file handle associated with my iostream? A: Using a combination of member functions fd() and rdbuf() you can get at the file handle. #include #define fstrno(s) (((s).rdbuf())->fd()) ifstream test("test.txt"); cout << "handle is " << fstrno(test) << '\n';

Developing PL/SQL Program Units (1Z0-101e)


Note :- These are only some of the questions which appear on this exam and not the complete Q pool. For complete stuff, mail at vicky74_vicky@yahoo.com Or vicky26_vicky@mail.com
1. The number of cascading triggers is limited by which data base initialization parameter?

a. CASCADE_TRIGGER_CNT b. OPEN_CURSORS ****

c. d.

OPEN_TRIGGERS OPEN_DB_TRIGGERS

2. Which type of package construct must be declared both within the package specifications and package body? a. b. c. d. 3. All package variables. Boolean variables. Private procedures and functions. Public procedures and functions. **** Why do stored procedures and functions improve performance? (choose two)

a. They reduce network round trips. **** b. They postpone PL/SQL parsing until run time. **** c. They allow the application to perform high speed processing locally. d. They reduce the number of calls to the database and decrease network traffic by bundling commands. e. They reduce the number of calls to the database and decrease network traffic by using the local PL/SQL engine. 4. When creating stored procedures and functions, which construct allows you to transfer values to and from the calling environment? a. b. c. d. Local variables. Formal arguments. **** Boolean variables. Substitution variables.

5. You need to remove the database trigger, BUSINESS_RULE. Which command do you use to remove the trigger in the SQL*Plus environment? a. DROP TRIGGER business_rule; **** b. DELETE TRIGGER business_rule; c. REMOVE TRIGGER business_rule; d. ALTER TRIGGER business_rule; e. DELETE FROM USER_TRIGGER WHERE TRIGGER_NAME= BUSINESS_RULE; 6. a. b. c. d. e. Which two tables are fused track object dependencies? USER_DEPENDENSIES. **** USER_IDEPTREE. IDEPTREE. **** USER_DEPTREE. USER_DEPENDS.

7. The QUERY_PRODUCT procedure directly references the product table. There is a NEW_PRODUCT_VIEW view created based on the NOT NULL columns of the table. The ADD_PRODUCT procedure updates the table indirectly by the way of NEW_PRODUCT_VIEW view. Under which circumstances does the procedureADD_PRODUCT get invalidated but automatically get complied when invoked? a. b. c. d. e. When the NEW_PRODUCT_VIEW is dropped. When rows of the product table are updated through SQL Plus. When the internal logic of the QUERY_PRODUCT procedure is modified. When a new column that can contain null values is added to the product table. **** When a new procedure is created that updates rows in the product table directly.

8. You need to recompile several program units you have recently modified through a PL/SQL program. Which statement is true? a. You cannot recompile program units using a PL/SQL program. b. You can use the DBMS_DDL. REOMPILE package procedure to recompile the program units. c. You can use the DBMS_ALTER. COMPILE packaged procedure to recompile the program units. d. You can use the DBMS_DDL.ALTER_COMPILE packaged procedure to recompile the program units. **** e. You can use the DBMS_SQL.ALTER_COMPILE packaged procedure to recompile the program units. 9. a. b. c. d. Which type of argument passes a value from a calling environment? VARCHER2 BOOLEAN OUT **** IN

10. You need to create a trigger on the EMP table that monitors every row that is changed and places this information into the AUDIT_TABLE. Which type of trigger do you create? a. Statement-level trigger on the EMP table. b. For each row trigger on the EMP table. **** c. Statement-level trigger on the AUDIT_TABLE table. d. For each row statement level trigger on the EMP table. eFor each row trigger on the AUDIT_TABLE table. 11. In order for you to create a run package, MAINTAIN_DATA, which privilege do you need? a. EXECUTE privilege on the MAINTAIN_DATA package. **** b. INVOKE privilege on the MAINTAIN_DATA package. c. EXECUTE privilege on the program units in the MAINTAIN_DATA package. d. Object privilege on all of the objects that the MAINTAIN_DATA package is accessing. e. Execute privilege on the program units inside the MAINTAIN_DATA package and execute privilege on the MAINTAIN_DATA package. 12. You have created a script file EMP_PROC.SQL that holds text to create a procedure, PROCESS_EMP. You have compiled the procedure for the SQL Plus environment by running the script file EMP_PROC.SQL. What happens if there are syntax errors in the procedure PROCESS_EMP? a. The errors are stored in the EMP_PROC.ERR file. b. The errors are displayed to the screen when the script file is run. c. The errors are stored in the PROCEDURE_ERRORS data dictionary view. d. You need to issue the SHOWERRORS command in the SQL Plus environment to see the errors. **** e. You need to issue the DISPLAY ERRORS command in the SQL Plus environment to see the errors. 13. Which statement about local dependent objects is true? a. b. c. d. They are on different nodes. They are in a different database. They are on the same node in the same database. **** They are on the same node in a different database.

14. You need to create a stored procedure that deletes rows from a table. The name of the table from

which the rows are to be deleted is unknown until run time. Which method do you implement while creating such a procedure? a. b. c. d. e. Use SQL command DELETE in the procedure to delete the rows. Use DBMS_SQL packaged routines in the procedure to delete the rows. **** Use DBMS_DML packaged routines in the procedure to delete the rows. Use DBMSDELETE packaged routines in the procedure to delete the rows. YOU cannot have a delete statement without providing a table name before compile time.

15. Under which situation do you create a server-side procedure? a. When the procedure contains no SQL statements. b. When the procedure contains no PL/SQL commands. c. When the procedure needs to be used by many client applications accessing several remote databases. d. When the procedure needs to be used by many users accessing the same schema objects on a local database. **** 16. Examine this procedure: CREATE OR REPLACE PROCEDURE ADD_PLAYER (V_ID IN NUMBER, V_LAST_NAME VARCHER2) IS BEGIN INSERT INTO PLAYER(ID,LAST_NAME). VALUES(V_ID,V_LAST_NAME); COMMIT; END; This procedure must invoke the UPD-STAT procedure and pass a parameter. Which statement will successfully invoke this procedure? a. b. c. d. EXECUTE UPD_BAT_STAT(V_ID); UPD_BAT_STAT(V_ID); **** RUN UPD_BAT_STAT(V_ID); START UPD_BAT_STAT(V_ID);

17. Match the purity levels to their correct definitions: Terms RNTS RNPS WNDS WNPS Definitions The function cannot modify the database tables. The function cannot change the values of the package variables. The function cannot query database tables. The function cannot reference the value of public packaged variables. 18. Examine this function: CREATE OR REPLACE FUNCTION CALC_PLAYER_AVG (V_ID in PLAYER_BAT_STAT. PLAYER_ID%TYPE) RETURN NUMBER IS V_AVG NUMBER;

SELECTS HITS/AT_BATS INTO V_AVG FROM PLAYER_BAT_STAT WHERE PLAYER_ID_V_ID; RETURN(V_AVG); END; This function must be moved to a package. Which additional statement must be added to the function to allow you to continue using the function in the GROUP BY clause of a SELECT statement? a. b. c. d. PRAGMA RESTRICT_REFERENCES (CALC_PLAYER_AVG, WNDS, WNPS); **** PRAGMA RESTRICT_REFERENCES (CALC_PLAYER_AVG, WNPS); PRAGMA RESTRICT_REFERENCES (CALC_PLAYER_AVG, RNPS, WNPS); PRAGMA RESTRICT_REFERENCES (CALC_PLAYER_AVG, ALLOW_GROUP_BY);

19. A programmer develops a procedure, ACCOUNT_TRANSACTION, and has left your company. You are assigned a task to modify this procedure. You want to find all the program units invoking the ACCOUNT_TRANSACTION procedure. How can you find this information? a. Query the USER_SOURCE data dictionary view. b. Query the USER_PROCEDURES data dictionary view. c. Query the USER_DEPENDENCIES data dictionary views. **** d. Set the SQL Plus environment variable trade code=true and run the ACCOUNT_TRANSACTION procedure. e. Set the SQL Plus environment variable DEPENDENCIES=TRUE and run the Account_Transaction procedure. 20. Examine this package. CREATE OR REPLACE PACKAGE BB_PACK IS V_MAX_TEAM_SALARY NUMBER(12,2); PROCEDURE ADD_PLAYER(V_ID NUMBER,V_LAST_NAME VARCHER2,V_SALARY NUMBER); END BB_PACK; / CREATE OR REPLACE PACKAGE BODY BB_PACK IS PROCEDURE UPD_PLAYER_STAT (V_ID IN NUMBER,V_AB_IN NUMBER DEFAULT4,V_HITS IN NUMBER) IS BEGIN UPDATE PLAYER_BAT_STAT SET AT_BATS+V_AB, HITS=HITS+V_HITS WHERE PLAYER_ID=V_ID; COMMIT; END UPD_PLAYER_STAT; PROCEDURE ADD_PLAYER (V_ID IN NUMBER,V_LAST_NAME VARCHER2,V_SALARY NUMBER) IS BEGIN INSERT INTO PLAYER(ID,LAST_NAME,SALARY); UPD_PLAYER_STAT(V_ID,0,0); END ADD PLAYER; END BB_PACK;

Which statement successfully assigns $75000000 to the V_MAX_TEAM_SALARY variable from within a stand alone procedure? a. b. c. d. V_MAX_TEAM_SALARY := 75000000; BB_PACK.ADD_PLAYER. V_MAX_TEAM_SALARY := 75000000; BB_PACK.V_MAX_TEAM_SALARY := 75000000; **** This variable cannot be assigned a value from outside the package.

21. Which two statements about the overloading feature of packages are true? a. Only local or packaged sub programs can be overloaded. **** b. Overloading allows different functions with the same name that differ only in their return types. c. Overloading allows different subprograms with the same number, type and order of the parameter. d. Overloading allows different subprograms with the same name and same number or type of the parameters. e. Overloading allows different subprograms with the same name but different in either number or type or order of parameters. **** 22. Examine this package: CREATE OR REPLACE manag emps IS Tax_rate CONSTANT NUMBER(5,2):= . 28:, V_id NUMBER; PROCEDURE insert_emp(p-deptno NUMBER,p-sal NUMBER); PROCEDURE delete_emp; PROCEDURE update_emp: FUNCTION calc_tax(o_sal NUMBER) RETURN NUMBER; END manag_emps; / CREATE REPLACE PACKAGE BODY manage_emps IS BEGIN Update emp. SET sal=|sal+p-raise_amt)+sal WHERE empno= v_id; END; PROCEDURE insert_emp (p_deptno NUMBER, p-sal NUMBER) IS BEGIN INSERT INTO emp(empno, deptno,sal) VALUES(v_id, p_deptno, p_sal); END insert emp; PROCEDURE delete_emp IS BEGIN DELETE FROM emp WHERE empno=v_id END delete_emp; PROCEDURE. Update_emp. IS V_sal NUMBER (10,2); V_raise NUMBER(10,2); BEGIN

SELECT Sal INTO v_sal FROM emp WHERE empno=v_id; IF v_sal<500 THEN V_raise:=0. 05; ELSIF v_sal<1000 THEN V_raise:=0. 07; ELSE V_raise:=0. 04 END IF; Update_sal(v_raise); END update_emp. FUNCTION calc_tax (p_sal NUMBER) RETURN NUMBER IS BEGIN RETURN p_sal* tax-rate; END calc_tax; END MANAGE_emp; / What is the name of the private procedure in the package? a. b. c. d. e. f. CALC_TAX INSERT_EMP UPDATE_SAL **** DELETE_EMP UPDATE_EMP MANAGE_EMP

23. Examine the code: CREATE OR REPLACE TRIGGER update_emp AFTER UPDATE ON emp BEGIN INSERT INTO audit_table (who, audited) VALUES(USER, SYSDATE); END; You issue an update command on the EMP table that results in changing ten rows. How many rows are inserted into the AUDIT_TABLE? a. b. c. d. 1 **** 10 none Value equal to the number of rows in the EMP table

24. All users currently have INSERT privileges on the PLAYER table. You want only your users to insert into this table using the ADD_PLAYER procedure. Which two actions must you take? a. b. c. d. e. GRANT SELECT ON ADD_PLAYER TO PUBLIC; GRANT EXECUTE ON ADD_PLAYER TO PUBLIC; **** GRANT INSERT ON PLAYER TO PUBLIC; GRANT EXECUTE, INSERT ON ADD_PLAYER TO PUBLIC; REVOKE INSERT ON PLAYER FROM PUBLIC; ****

25. Which oracle supply package allows you to run jobs that use defined times? a. b. c. d. DBMS_JOB **** DBMS_RUN DBMS_PIPE DBMS_SQL

26. You need to drop a table from within a stored procedure. How do you implement this? a. b. c. d. e. You cannot drop a table from a stored procedure. Use the DROP command in the procedure to drop the table. Use the DBMS_DDL packaged routines in the procedure to drop the table. Use the DBMS_SQL packaged routines in the procedure to drop the table. **** Use the DBMS_DROP packaged routines in the procedure to drop the table.

27. Which data dictionary view gives you the names and the source code of all the procedures you have created? a. b. c. d. USER_SOURCE **** USER_OBJECTS USER_PROCEDURES USER_SUBPROGRAMS

28. Examine this package: CREATE OR REPLACE PACKAGE BB_PACK IS V_MAX_TEAM_SALARY NUMBER(12,2); PROCEDURE ADD_PLAYER(V_ID IN NUMBER, V_LAST_NAME) VARCHAR2(V_SALARY NUMBER); END BB_PACK; / CREATE OR REPLACE PACKAGE BODY BB_PACK IS V_PLAYER_AVG NUMBER(4,3); PROCEDURE UPD_PLAYER_STAT V_ID IN NUMBER, V_AB IN NUMBER DEFAULT4, V_HITS IN NUMBER) IS BEGIN UPDATE PLAYER_BAT_STAT SET ADD_BAT=ADD_BATS+V_AB, HITS=HITS+V_HITS WHERE PLAYER_ID=V_ID; COMMIT; VALIDATE_PLAYER_STAT(V_ID); END UPD_PLAYER_STAT; PROCEDURE ADD_PLAYER (V_ID IN NUMBER, V_LAST_NAME, VARCHAR2, V_SALARY IN NUMBER); IS BEGIN INSERT INTO PLAYER (ID, LAST_NAME, SALARY) VALUES(V_ID, V_LAST_NAME, V_SALARY); UPD_PLAYER_STAT(V_ID,0,0); END ADD_PLAYER; END BB_PACK; Which kind of packaged variable is V_MAX_TEAM_SALARY?

a. b. c. d.

PRIVATE PUBLIC **** IN OUT

29. Examine this trigger: CREATE OR REPLACE TRIGGER UPD_TEAM_SALARY AFTER INSERT OR UPDATE OR DELETE ON PLAYER FOR EACH ROW BEGIN UPDATE TEAM SET TOT_SALARY=TOT_SALARY+:NEW SALARY. WHERE ID=:NEW:TEAM_ID; You will be adding additional code later but for now you want the current block to fire when updating the salary column. Which solution should you use to verify that the user is performing an update on the salary column? a. b. c. d. ROW_UPDATE(SALARY) UPDATING(SALARY) **** CHANGING(SALARY) COLUMN_UPDATE(SALARY)

30. Examine this package: CREATE OR REPLACE PACKAGE discounts IS G_ID NUMBER:=7839; DISCOUNT_RATE NUMBER O. 00; PROCEDURE DISPLAY_PRICE (V_PRICE NUMBER); END DISCOUNTS; / CREATE OR REPLACE PACKAGE BODY discounts IS PROCEDURE DISPLAY_PRICE (V_PRICE_NUMBER) IS BEGIN DBMS_OUTPUT.PUT_LINE(DISCOUNTED||2_4 (V_PRICE*NVL(DISCOUNT_RATE, 1))) END DISPLAY_PRICE; BEGIN DISCOUNT_RATE;=0. 10; END DISCOUNTS; / Which statement is true? a. The value of DISCOUNT_RATE always remain 0.00 in a session. b. The value of DISCOUNT_RATE is set to 0.10 each time the package is invoked in a session. c. The value of DISCOUNT_RATE is set to 1 each time the procedure DISPLAY_PRICE is invoked. d. The value of DISCOUNT_RATE is set to 0.10 when the package is invoked for the first time in a session. **** 31. Examine this package: CREATE OR REPLACE PACKAGE BB_PACK V_MAX_TEAM_SALARY NUMBER(12,2); PROCEDURE ADD_PLAYER(V_ID IN NUMBER, V_LAST_NAME VARCHAR2, V_SALARY NUMBER);

DB_PACK;/ CREATE OR REPLACE PACKAGE BODY BB_PACK IS V_WHERE_AVG NUMBER(4,3); PROCEDURE UPD_PLAYER_STAT (V_ID IN NUMBER, V_AVG IN NUMBER DEFAULT 4,V_HITS IN NUMBER) IS BEGIN UPDATE PLAYER_BAT_STAT SET AT_BATS=AT_BATS+V_AB, HITS=HITS+V_HITS WHERE PLAYER_ID=V_ID; COMMIT; VALIDATE_PLAYER_STAT(V_ID); END UPD_PLAYER_STAT; PROCEDURE ADD-PLAYER (V_ID IN NUMBER, V_LAST_NAME VARCHAR2, V_SALARY NUMBER) IS BEGIN INSERT INTO PLAYER(ID, LAST_NAME, SALARY) VALUES(V_ID, V_LAST_NAME, V_SALARY); UPD_PLAYER_STAT(V_ID,0,0); END ADD_PLAYER; END BB_PACK; An outside procedure VALIDATE_PLAYER_STAT is executed from this package. What will happen when this procedure changes? a. The package specification is dropped. b. The package specification is invalidated. c. The package is invalid to begin with. d. The package body is invalidated ****

Вам также может понравиться