These material are compiled for helping junior / senior software engineers and others.

1. Write a short code using C++ to print out all odd number from 1 to 100 using a for loop

for( unsigned int i = 1; i < = 100; i++ )
    if( i & 0x00000001 )
        cout << i << \",\";

2. ISO layers and what layer is the IP operated from?

cation, Presentation, Session, Transport, Network, Data link and Physical. The IP is operated in the Network layer.

3. Write a program that ask for user input from 5 to 9 then calculate the average main()
int MAX=4;
int total =0;
int average=0;
int numb;
cout << "Please enter your input from 5 to 9";
cin << numb;
if((numb < 5)&&(numb < 9))
cout << "please re type your input";
for(i=0;i < =MAX; i++)
total = total + numb;
average= total /MAX;
cout << "The average number is" << average << endl;

return 0;

4. Can you be bale to identify between Straight- through and Cross- over cable wiring? and in what case do you use Straight- through and Cross-over?

Straight-through is type of wiring that is one to to one connection Cross- over is type of wiring which those wires are got switched
We use Straight-through cable when we connect between NIC Adapter and Hub. Using Cross-over cable when connect between two NIC Adapters or sometime between two hubs.

5. If you hear the CPU fan is running and the monitor power is still on, but you did not see any thing show up in the monitor screen. What would you do to find out what is going wrong?

I would use the ping command to check whether the machine is still alive(connect to the network) or it is dead.

6. How do you write a function that can reverse a linked-list?

void reverselist(void)
		head->next = 0;
		tail->next = head;
		node* pre = head;
		node* cur = head->next;
		node* curnext = cur->next;
		head->next = 0;
		cur-> next = head;

		for(; curnext!=0; )
			cur->next = pre;
			pre = cur;
			cur = curnext;
			curnext = curnext->next;

		curnext->next = cur;

7. What is polymorphism?

Polymorphism is the idea that a base class can be inherited by several classes. A base class pointer can point to its child class and a base class array can store different child class objects.

8. How do you find out if a linked-list has an end? (i.e. the list is not a cycle)

You can find out by using 2 pointers. One of them goes 2 nodes each time. The second one goes at 1 nodes each time. If there is a cycle, the one that goes 2 nodes each time will eventually meet the one that goes slower. If that is the case, then you will know the linked-list is a cycle.

9. How can you tell what shell you are running on UNIX system?

You can do the Echo $RANDOM. It will return a undefined variable if you are from the C-Shell, just a return prompt if you are from the Bourne shell, and a 5 digit random numbers if you are from the Korn shell. You could also do a ps -l and look for the shell with the highest PID.

10. What is Boyce Codd Normal form?

A relation schema R is in BCNF with respect to a set F of functional dependencies if for all functional dependencies in F+ of the form a-> , where a and b is a subset of R, at least one of the following holds:
* a- > b is a trivial functional dependency (b is a subset of a)
* a is a superkey for schema R

11. Tell how to check whether a linked list is circular.

Create two pointers, each set to the start of the list. Update each as follows:

while (pointer1) {
 pointer1 = pointer1->next;
 pointer2 = pointer2->next; if (pointer2) pointer2=pointer2->next;
 if (pointer1 == pointer2) {
   print (\"circular\n\");

OK, why does this work? If a list is circular, at some point pointer2 will wrap around and be either at the item just before pointer1, or the item before that. Either way, its either 1 or 2 jumps until they meet.

13. 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.

14. 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.

15. What is a template?

Templates allow to create generic functions that admit any data type as parameters and return value without having to overload the function with all the possible data types. Until certain point they fulfill the functionality of a macro. Its prototype is any of the two following ones:
template 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.

16. 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.

17. What is RTTI?

Runtime type identification (RTTI) lets you find the dynamic type of an object when you have only a pointer or a reference to the base type. RTTI is the official way in standard C++ to discover the type of an object and to convert the type of a pointer or reference (that is, dynamic typing). The need came from practical experience with C++. RTTI replaces many homegrown versions with a solid, consistent approach.

18. What is encapsulation?

Packaging an objects variables within its methods is called encapsulation.

19. What is an object?

Object is a software bundle of variables and related methods. Objects have state and behavior.

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 namespace?

Namespaces allow us to group a set of global classes, objects and/or functions under a name. To say it somehow, they serve to split the global scope in sub-scopes known as namespaces.
The form to use namespaces is:
namespace identifier { namespace-body }
Where identifier is any valid identifier and namespace-body is the set of classes, objects and functions that are included within the namespace. For example:
namespace general { int a, b; } In this case, a and b are normal variables integrated within the general namespace. In order to access to these variables from outside the namespace we have to use the scope operator ::. For example, to access the previous variables we would have to put:
general::a general::b
The functionality of namespaces is specially useful in case that there is a possibility that a global object or function can have the same name than another one, causing a redefinition error.

22. 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.

23. What is function overloading and operator overloading?

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).

24. 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.

25. What do you mean by binding of data and functions?


26. 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.

27. 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.

28. 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.

29. What is abstraction?

Abstraction is of the process of hiding unwanted details from the user.

30. 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.

31. What is a scope resolution operator?

A scope resolution operator (::), can be used to define the member functions of a class outside the class.

32. What do you mean by pure virtual functions?

A pure virtual member function is a member function that the base class forces derived classes to provide. Normally these member functions have no implementation. Pure virtual functions are equated to zero.
class Shape { public: virtual void draw() = 0; };

33. 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.

34. How can you quickly find the number of elements stored in a a) static array b) dynamic array ?
Why is it difficult to store linked list in an array?
How can you find the nodes with repetetive data in a linked list?

Write a prog to accept a given string in any order and flash error if any of the character is different. For example : If abc is the input then abc, bca, cba, cab bac are acceptable but aac or bcd are unacceptable.
Write out a function that prints out all the permutations of a string. For example, abc would give you abc, acb, bac, bca, cab, cba. You can assume that all the characters will be unique.

35. Whats the output of the following program? Why?

#include <stdio.h>
	typedef union
		int a;
		char b[10];
		float c;

	Union x,y = {100};
	x.a = 50;
	x.c = 21.50;

	printf(\"Union x : %d %s %f \n\",x.a,x.b,x.c );
	printf(\"Union y :%d %s%f \n\",y.a,y.b,y.c);

Given inputs X, Y, Z and operations | and & (meaning bitwise OR and AND, respectively)
What is output equal to in
output = (X & Y) | (X & Z) | (Y & Z)

36. Explain which of the following declarations will compile and what will be constant - a pointer or the value pointed at: * const char *
* char const *
* char * const

Note: Ask the candidate whether the first declaration is pointing to a string or a single character. Both explanations are correct, but if he says that its a single character pointer, ask why a whole string is initialized as char* in C++. If he says this is a string declaration, ask him to declare a pointer to a single character. Competent candidates should not have problems pointing out why const char* can be both a character and a string declaration, incompetent ones will come up with invalid reasons.

37. Youre given a simple code for the class BankCustomer. Write the following functions:
* Copy constructor
* = operator overload
* == operator overload
* + operator overload (customers balances should be added up, as an example of joint account between husband and wife)

Note:Anyone confusing assignment and equality operators should be dismissed from the interview. The applicant might make a mistake of passing by value, not by reference. The candidate might also want to return a pointer, not a new object, from the addition operator. Slightly hint that youd like the value to be changed outside the function, too, in the first case. Ask him whether the statement customer3 = customer1 + customer2 would work in the second case.

38. What problems might the following macro bring to the application?

#define sq(x) x*x

39. Consider the following struct declarations:

struct A { A(){ cout << \"A\"; } };
struct B { B(){ cout << \"B\"; } };
struct C { C(){ cout << \"C\"; } };
struct D { D(){ cout << \"D\"; } };
struct E : D { E(){ cout << \"E\"; } };
struct F : A, B
	C c;
	D d;
	E e;
	F() : B(), A(),d(),c(),e() { cout << \"F\"; }

40. What constructors will be called when an instance of F is initialized?

Produce the program output when this happens.

41. Anything wrong with this code?
T *p = new T[10];
delete p;

Note: Incorrect replies: No, everything is correct, Only the first element of the array will be deleted, The entire array will be deleted, but only the first element destructor will be called.

42. Anything wrong with this code?
T *p = 0;
delete p;

Note: Typical wrong answer: Yes, the program will crash in an attempt to delete a null pointer. The candidate does not understand pointers. A very smart candidate will ask whether delete is overloaded for the class T.

43. Explain virtual inheritance. Draw the diagram explaining the initialization of the base class when virtual inheritance is used.

Note: Typical mistake for applicant is to draw an inheritance diagram, where a single base class is inherited with virtual methods. Explain to the candidate that this is not virtual inheritance. Ask them for the classic definition of virtual inheritance. Such question might be too complex for a beginning or even intermediate developer, but any applicant with advanced C++ experience should be somewhat familiar with the concept, even though hell probably say hed avoid using it in a real project. Moreover, even the experienced developers, who know about virtual inheritance, cannot coherently explain the initialization process. If you find a candidate that knows both the concept and the initialization process well, hes hired.

44. Whats potentially wrong with the following code?
long value;
//some stuff
value &= 0xFFFF;

Note: Hint to the candidate about the base platform theyre developing for. If the person still doesnt find anything wrong with the code, they are not experienced with C++.

45. What does the following code do and why would anyone write something like that?

void send (int *to, int * from, int count)
	int n = (count + 7) / 8;
	switch ( count  %  8)
		case 0: do { *to++ = *from++;
		case 7: *to++ = *from++;
		case 6: *to++ = *from++;
		case 5: *to++ = *from++;
		case 4: *to++ = *from++;
		case 3: *to++ = *from++;
		case 2: *to++ = *from++;
		case 1: *to++ = *from++;
		} while ( --n > 0 );

46. In the H file you see the following declaration:
class Foo {
void Bar( void ) const ;
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 derived-class 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.

47. Does c++ support multilevel and multiple inheritance?


48. 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.

49. 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 << endl; }

C/C++ Questions only

1. What is the output of printf("%d")
2. What will happen if I say delete this
3. Difference between "C structure" and "C++ structure".
4. Diffrence between a "assignment operator" and a "copy constructor"
5. What is the difference between "overloading" and "overridding"?
6. Explain the need for "Virtual Destructor".
7. Can we have "Virtual Constructors"?
8. What are the different types of polymorphism?
9. What are Virtual Functions? How to implement virtual functions in "C"
10. What are the different types of Storage classes?
11. What is Namespace?
12. What are the types of STL containers?.
13. Difference between "vector" and "array"?
14. How to write a program such that it will delete itself after exectution?
15. Can we generate a C++ source code from the binary file?
16. What are inline functions?
17. Talk sometiming about profiling?
18. How many lines of code you have written for a single program?
19. What is "strstream" ?
20. How to write Multithreaded applications using C++?
21. Explain "passing by value", "passing by pointer" and "passing by reference"
22. Write any small program that will compile in "C" but not in "C++"
23. Have you heard of "mutable" keyword?
24. What is a "RTTI"?
25. Is there something that I can do in C and not in C++?
26. Why preincrement operator is faster than postincrement?
27. What is the difference between "calloc" and "malloc"?
28. What will happen if I allocate memory using "new" and free it using "free" or allocate sing "calloc" and free it using "delete"?
29. What is Memory Alignment?
30. Explain working of printf.
31. Difference between "printf" and "sprintf".
32. What is "map" in STL?
33. When shall I use Multiple Inheritance?
34. What are the techniques you use for debugging?
35. How to reduce a final size of executable?
36. Give 2 examples of a code optimization.

C/C++ Questions only (Declarations and Initializations)

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

2. What should the 64-bit type on new, 64-bit machines be?

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

4. What does extern mean in a function declaration?

5. What's the auto keyword good for?

6. How do I declare an array of N pointers to functions returning

pointers to functions returning pointers to characters?

7. How can I declare a function that returns a pointer to a function

of its own type?

8. My compiler is complaining about an invalid redeclaration of a

function, but I only define it once and call it once.

9. What can I safely assume about the initial values of variables

which are not explicitly initialized?

10. Why can't I initialize a local array with a string?

11. What is the difference between char a[] = "string"; and char *p =

"string"; ?

12. How do I initialize a pointer to a function?    

C/C++ Questions only (Structures, Unions, and Enumerations)

1. What's the difference between struct x1 { ... }; and typedef

struct { ... } x2; ?

2. Why doesn't "struct x { ... }; x thestruct;" work?

3. Can a structure contain a pointer to itself?

4. What's the best way of implementing opaque (abstract) data types

in C?

5. I heard that structures could be assigned to variables and passed

to and from functions, but K&R1 says not.

6. Why can't you compare structures?

7. How are structure passing and returning implemented?

8. Can I pass constant values to functions which accept structure


9. How can I read/write structures from/to data files?

10. How can I turn off structure padding?

11. Why does sizeof report a larger size than I expect for a

structure type?

12. How can I determine the byte offset of a field within a


13. How can I access structure fields by name at run time?

14 I have a program which works correctly, but dumps core after it

finishes. Why?

15. Can I initialize unions?

16. What is the difference between an enumeration and a set of

preprocessor #defines?

17. Is there an easy way to print enumeration values symbolically?

C/C++ Questions only (Expressions)

1. Why doesn't the code "a[i] = i++;" work?

2. Under my compiler, the code "int i = 7; printf("%d\n", i++ *

i++);" prints 49. Regardless of the order of evaluation, shouldn't it

print 56?

3. How could the code [CENSORED] ever give 7?

4. Don't precedence and parentheses dictate order of evaluation?

5. But what about the && and || operators?

6. What's a ``sequence point''?

7. So given "a[i] = i++;" we don't know which cell of a[] gets

written to, but i does get incremented by one.

8. If I'm not using the value of the expression, should I use i++ or

++i to increment a variable?

9. Why doesn't the code "int a = 1000, b = 1000; long int c = a *

b;" work?

10. Can I use ?: on the left-hand side of an assignment expression?

C/C++ Questions only (Pointers)

1. What's wrong with "char *p; *p = malloc(10);"?

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

3. I want to use a char * pointer to step over some ints. Why doesn't

"((int *)p)++;" work?

4. I have a function which accepts, and is supposed to initialize, a

pointer, but the pointer in the caller remains unchanged.

5. Can I use a void ** pointer to pass a generic pointer to a

function by reference?

6. I have a function which accepts a pointer to an int. How can I

pass a constant like 5 to it?

7. Does C even have ``pass by reference''?

8. I've seen different methods used for calling functions via

C/C++ Questions only (Null Pointers)

1. What is this infamous null pointer, anyway?

2. How do I get a null pointer in my programs?

3. Is the abbreviated pointer comparison ``if(p)'' to test for

non-null pointers valid?

4. What is NULL and how is it #defined?

5. How should NULL be defined on a machine which uses a nonzero bit

pattern as the internal representation of a null pointer?

6. If NULL were defined as ``((char *)0),'' wouldn't that make

function calls which pass an uncast NULL work?

7. If NULL and 0 are equivalent as null pointer constants, which

should I use?

8. But wouldn't it be better to use NULL, in case the value of NULL


9. I use the preprocessor macro "#define Nullptr(type) (type *)0" to

help me build null pointers of the correct type.

10. This is strange. NULL is guaranteed to be 0, but the null pointer

is not?

11. Why is there so much confusion surrounding null pointers?

12. I'm confused. I just can't understand all this null pointer


13. Given all the confusion surrounding null pointers, wouldn't it be

easier simply to require them to be represented internally by zeroes?

14. Seriously, have any actual machines really used nonzero null


15. What does a run-time ``null pointer assignment'' error mean?

C/C++ Questions only (Arrays and Pointers)

1. I had the definition char a[6] in one source file, and in another

I declared extern char *a. Why didn't it work?

2. But I heard that char a[] was identical to char *a.

3. So what is meant by the ``equivalence of pointers and arrays'' in


4. Why are array and pointer declarations interchangeable as function

formal parameters?

5. How can an array be an lvalue, if you can't assign to it?

6. What is the real difference between arrays and pointers?

7. Someone explained to me that arrays were really just constant


8. I came across some ``joke'' code containing the ``expression''

5["abcdef"] . How can this be legal C?

9. What's the difference between array and &array?

10. How do I declare a pointer to an array?

11. How can I set an array's size at compile time?

12. How can I declare local arrays of a size matching a passed-in


13. How can I dynamically allocate a multidimensional array?

14. Can I simulate a non-0-based array with a pointer?

15. My compiler complained when I passed a two-dimensional array to a

function expecting a pointer to a pointer.

16. How do I write functions which accept two-dimensional arrays when

the ``width'' is not known at compile time?

17. How can I use statically- and dynamically-allocated

multidimensional arrays interchangeably when passing them to


18. Why doesn't sizeof properly report the size of an array which is

a parameter to a

C/C++ Questions only (Memory Allocation)

1. Why doesn't the code ``char *answer; gets(answer);'' work?

2. I can't get strcat to work. I tried ``char *s3 = strcat(s1, s2);''

but I got strange results.

3. But the man page for strcat says that it takes two char *'s as

arguments. How am I supposed to know to allocate things?

4. I have a function that is supposed to return a string, but when it

returns to its caller, the returned string is garbage.

5. Why am I getting ``warning: assignment of pointer from integer

lacks a cast'' for calls to malloc?


6. Why does some code carefully cast the values returned by malloc to

the pointer type being allocated?

7. Why does so much code leave out the multiplication by sizeof(char)

when allocating strings?

8. I've heard that some operating systems don't actually allocate

malloc'ed memory until the program tries to use it. Is this legal?

9. I'm allocating a large array for some numeric work, but malloc is

acting strangely.

10. I've got 8 meg of memory in my PC. Why can I only seem to malloc

640K or so?

19 My program is crashing, apparently somewhere down inside malloc.

11. You can't use dynamically-allocated memory after you free it, can


12. Why isn't a pointer null after calling free?

13. When I call malloc to allocate memory for a local pointer, do I

have to explicitly free it?

14. When I free a dynamically-allocated structure containing

pointers, do I have to free each subsidiary pointer first?

15. Must I free allocated memory before the program exits?

16. Why doesn't my program's memory usage go down when I free memory?

17. How does free know how many bytes to free?

18. So can I query the malloc package to find out how big an

allocated block is?

19. Is it legal to pass a null pointer as the first argument to


20. What's the difference between calloc and malloc?

21. What is alloca and why is its use discouraged?

C/C++ Questions only (Characters and Strings)

1. Why doesn't "strcat(string, '!');" work?

2. Why won't the test if(string == "value") correctly compare string

against the value?

3. Why can't I assign strings to character arrays?

4. How can I get the numeric (character set) value corresponding to a


5. Why is sizeof('a') not

C/C++ Questions only (Boolean Expressions and Variables)

1. What is the right type to use for Boolean values in C?

2. What if a built-in logical or relational operator ``returns''

something other than 1?

3. Is if(p), where p is a pointer,

C/C++ Questions only (C Preprocessor)

1. I've got some cute preprocessor macros that let me write C code

that looks more like Pascal. What do y'all think?

2. How can I write a generic macro to swap two values?

3. What's the best way to write a multi-statement macro?

4. What are .h files and what should I put in them?

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

6. Where are header (``#include'') files searched for?

7. I'm getting strange syntax errors on the very first declaration

in a file, but it looks fine.

8. Where can I get a copy of a missing header file?

9. How can I construct preprocessor #if expressions which compare


10. Does the sizeof operator work in preprocessor #if directives?

11. Can I use an #ifdef in a #define line, to define something two

different ways?

12. Is there anything like an #ifdef for typedefs?

13. How can I use a preprocessor #if expression to detect


14. How can I preprocess some code to remove selected conditional

compilations, without preprocessing everything?

15. How can I list all of the pre#defined identifiers?

16. I have some old code that tries to construct identifiers with a

17. macro like "#define Paste(a, b) a/**/b", but it doesn't work any more.


What does the message ``warning: macro replacement within a string

literal'' mean?

19. How can I use a macro argument inside a string literal in the

macro expansion?

20. I've got this tricky preprocessing I want to do and I can't

figure out a way to do it.

21. How can I write a macro which takes a variable number of

C/C++ Questions only (ANSI/ISO Standard C)

1. What is the ``ANSI C Standard?''

2. How can I get a copy of the Standard?

3. My ANSI compiler is complaining about prototype mismatches for

parameters declared float.

4. Can you mix old-style and new-style function syntax?

5. Why does the declaration "extern f(struct x *p);" give me a

warning message?

6. Why can't I use const values in initializers and array


7. What's the difference between const char *p and char * const p?

8. Why can't I pass a char ** to a function which expects a const

char **?

9. Can I declare main as void, to shut off these annoying ``main

returns no value'' messages?

10. But what about main's third argument, envp?

11. I believe that declaring void main() can't fail, since I'm

calling exit instead of returning.

12. The book I've been using always uses void main().

13. Is exit(status) truly equivalent to returning the same status

from main?

14. How do I get the ANSI ``stringizing'' preprocessing operator `#'

to stringize the macro's value instead of its name?

15. What does the message ``warning: macro replacement within a

string literal'' mean?

16. I'm getting strange syntax errors inside lines I've #ifdeffed


17. What are #pragmas ?

What does ``#pragma once'' mean?

18. Is char a[3] = "abc"; legal?

19. Why can't I perform arithmetic on a void * pointer?

20. What's the difference between memcpy and memmove?

21. What should malloc(0) do?

22. Why does the ANSI Standard not guarantee more than six

case-insensitive characters of external identifier significance?

23. My compiler is rejecting the simplest possible test programs,

with all kinds of syntax errors.

24. Why are some ANSI/ISO Standard library routines showing up as

undefined, even though I've got an ANSI compiler?

25. Does anyone have a tool for converting old-style C programs to

ANSI C, or for automatically generating prototypes?

26. Why won't frobozz-cc, which claims to be ANSI compliant, accept

this code?

27. What's the difference between implementation-defined,

unspecified, and undefined behavior?

28. I'm appalled that the ANSI Standard leaves so many issues


29. I just tried some allegedly-undefined code on an ANSI-conforming

compiler, and got the results I expected.

C/C++ Questions only (Stdio)

1. What's wrong with the code "char c; while((c = getchar()) != EOF)


2. Why won't the code `` while(!feof(infp)) { fgets(buf, MAXLINE,

infp); fputs(buf, outfp); } '' work?

3. My program's prompts and intermediate output don't always show up

on the screen.

4. How can I read one character at a time, without waiting for the


5. How can I print a '%' character with printf?

6. How can printf use %f for type double, if scanf requires %lf?

7. How can I implement a variable field width with printf?

8. How can I print numbers with commas separating the thousands?

9. Why doesn't the call scanf("%d", i) work?

10. Why doesn't the code "double d; scanf("%f", &d);" work?

11. How can I specify a variable width in a scanf format string?

12. When I read numbers from the keyboard with scanf "%d\n", it

seems to hang until I type one extra line of input.

13. I'm reading a number with scanf %d and then a string with

gets(), but the compiler seems to be skipping the call to gets()!

14. I'm re-prompting the user if scanf fails, but sometimes it seems

to go into an infinite loop.

15. Why does everyone say not to use scanf? What should I use


16. How can I tell how much destination buffer space I'll need for

an arbitrary sprintf call? How can I avoid overflowing the destination

buffer with sprintf?

17. Why does everyone say not to use gets()?

18. Why does errno contain ENOTTY after a call to printf?

19. What's the difference between fgetpos/fsetpos and ftell/fseek?

20. Will fflush(stdin) flush unread characters from the standard

input stream?

21. I'm trying to update a file in place, by using fopen mode "r+",

but it's not working.

22. How can I redirect stdin or stdout from within a program?

23. Once I've used freopen, how can I get the original stream back?

24. How can I read a binary data file properly?

C/C++ Questions only (Library Functions)

1. How can I convert numbers to strings?

2. Why does strncpy not always write a '\0'?

3. Why do some versions of toupper act strangely if given an

upper-case letter?

4. How can I split up a string into whitespace-separated fields?

5. I need some code to do regular expression and wildcard matching.

6. I'm trying to sort an array of strings with qsort, using strcmp

as the comparison function, but it's not working.

7. Now I'm trying to sort an array of structures, but the compiler

is complaining that the function is of the wrong type for qsort.

8. How can I sort a linked list?

9. How can I sort more data than will fit in memory?

10. How can I get the time of day in a C program?

11. How can I convert a struct tm or a string into a time_t?

12. How can I perform calendar manipulations?

13. I need a random number generator.

14. How can I get random integers in a certain range?

15. Each time I run my program, I get the same sequence of numbers

back from rand().

16. I need a random true/false value, so I'm just taking rand() % 2,

but it's alternating 0, 1, 0, 1, 0...

17. How can I generate random numbers with a normal or Gaussian


18. I'm trying to port this old program. Why do I get ``undefined

external'' errors for some library functions?

19. I get errors due to library functions being undefined even

though I #include the right header files.

20. I'm still getting errors due to library functions being

undefined, even though I'm requesting the right libraries.

21. What does it mean when the linker says that _end is undefined?

C/C++ Questions only (Floating Point)

1. When I set a float variable to 3.1, why is printf printing it as


2. Why is sqrt(144.) giving me crazy numbers?

3. I keep getting ``undefined: sin'' compilation errors.

4. My floating-point calculations are acting strangely and giving me

different answers on different machines.

5. What's a good way to check for ``close enough'' floating-point


6. How do I round numbers?

7. Where is C's exponentiation operator?

8. The pre-#defined constant M_PI seems to be missing from <math.h>.

9. How do I test for IEEE NaN and other special values?

10. What's a good way to implement complex numbers in C?

11. I'm looking for some mathematical library code.

12. I'm having trouble with a Turbo C program which crashes and says

something like ``floating point formats not linked.''

C/C++ Questions only (Variable-Length Argument Lists)

1. I heard that you have to #include <stdio.h> before calling

printf. Why?

2. How can %f be used for both float and double arguments in printf?

3. Why don't function prototypes guard against mismatches in

printf's arguments?

4. How can I write a function that takes a variable number of


5. How can I write a function that takes a format string and a

variable number of arguments, like printf, and passes them to printf

to do most of the work?

6. How can I write a function analogous to scanf, that calls scanf

to do most of the work?

7. I have a pre-ANSI compiler, without <stdarg.h>. What can I do?

8. How can I discover how many arguments a function was actually

called with?

9. My compiler isn't letting me declare a function that accepts only

variable arguments.

10. Why isn't "va_arg(argp, float)" working?

11. I can't get va_arg to pull in an argument of type


12. How can I write a function which takes a variable number of

arguments and passes them to some other function ?

13. How can I call a function with an argument list built up at run


C/C++ Questions only (Strange Problems)

1. This program crashes before it even runs!

2. I have a program that seems to run correctly, but then crashes as

it's exiting.

3. This program runs perfectly on one machine, but I get weird

results on another.

4. Why does the code "char *p = "hello, world!"; p[0] = 'H';" crash?

5. What does ``Segmentation violation'' mean?

C/C++ Questions only (Style)

1. What's the best style for code layout in C?

2. Is the code "if(!strcmp(s1, s2))" good style?

3. Why do some people write if(0 == x) instead of if(x == 0)?

4. I came across some code that puts a (void) cast before each call

to printf. Why?

5. What is Hungarian Notation''? Is it worthwhile?

6. Where can I get the ``Indian Hill Style Guide'' and other coding


7. Some people say that goto's are evil and that I should never use

them. Isn't that a bit extreme?

C/C++ Questions only (Tools and Resources)

1. I'm looking for C development tools (cross-reference generators,

code beautifiers, etc.).

2. How can I track down these pesky malloc problems?

3. What's a free or cheap C compiler I can use?

4. I just typed in this program, and it's acting strangely. Can you

see anything wrong with it?

5. How can I shut off the ``warning: possible pointer alignment

problem'' message which lint gives me for each call to malloc?

7. Where can I get an ANSI-compatible lint?

8. Don't ANSI function prototypes render lint obsolete?

9. Are there any C tutorials or other resources on the net?

10. What's a good book for learning C?

11. Where can I find the sources of the standard C libraries?

12. I need code to parse and evaluate expressions.

13. Where can I get a BNF or YACC grammar for C?

14. Does anyone have a C compiler test suite I can use?

15. Where and how can I get copies of all these freely distributable


C/C++ Questions only (System Dependencies)

1. How can I read a single character from the keyboard without

waiting for the RETURN key?

2. How can I find out how many characters are available for reading,

or do a non-blocking read?

3. How can I display a percentage-done indication that updates

itself in place, or show one of those ``twirling baton'' progress


4. How can I clear the screen, or print things in inverse video, or

move the cursor?

5. How do I read the arrow keys? What about function keys?

6. How do I read the mouse?

7. How can I do serial (``comm'') port I/O?

8. How can I direct output to the printer?

9. How do I send escape sequences to control a terminal or other


10. How can I do graphics?

11. How can I check whether a file exists?

12. How can I find out the size of a file, prior to reading it in?

13. How can a file be shortened in-place without completely clearing

or rewriting it?

14. How can I insert or delete a line in the middle of a file?

15. How can I recover the file name given an open file descriptor?

16. How can I delete a file?

17. What's wrong with the call "fopen("c:\newdir\file.dat", "r")"?

18. How can I increase the allowable number of simultaneously open


19. How can I read a directory in a C program?

20. How can I find out how much memory is available?

21. How can I allocate arrays or structures bigger than 64K?

22. What does the error message ``DGROUP exceeds 64K'' mean?

23. How can I access memory located at a certain address?

24. How can I invoke another program from within a C program?

25. How can I invoke another program and trap its output?

26. How can my program discover the complete pathname to the

executable from which it was invoked?

27. How can I automatically locate a program's configuration files

in the same directory as the executable?

28. How can a process change an environment variable in its caller?

29. How can I read in an object file and jump to routines in it?

30. How can I implement a delay, or time a user's response, with

sub-second resolution?

31. How can I trap or ignore keyboard interrupts like control-C?

32. How can I handle floating-point exceptions gracefully?

33. How do I... Use sockets? Do networking? Write client/server


34. How do I use BIOS calls? How can I write ISR's? How can I

create TSR's?

35. But I can't use all these nonstandard, system-dependent

functions, because my program has to be ANSI compatible!

C/C++ Questions only (Miscellaneous)

1. How can I return multiple values from a function?

2. How do I access command-line arguments?

3. How can I write data files which can be read on other machines

with different data formats?

4. How can I call a function, given its name as a string?

5. How can I implement sets or arrays of bits?

6. How can I determine whether a machine's byte order is big-endian

or little-endian?

7. How can I convert integers to binary or hexadecimal?

8. Can I use base-2 constants (something like 0b101010)?

Is there a printf format for binary?

9. What is the most efficient way to count the number of bits which

are set in a value?

10. How can I make my code more efficient?

11. Are pointers really faster than arrays? How much do function

calls slow things down?

12. Is there a way to switch on strings?

13. Is there a way to have non-constant case labels (i.e. ranges or

arbitrary expressions)?

14. Are the outer parentheses in return statements really optional?

15. Why don't C comments nest? Are they legal inside quoted strings?

16. Why doesn't C have nested functions?

17. How can I call FORTRAN (C++, BASIC, Pascal, Ada, LISP) functions from C?

16. Does anyone know of a program for converting Pascal or FORTRAN to C?

17. Can I use a C++ compiler to compile C code?

18. I need to compare two strings for close, but not necessarily exact, equality.

19. What is hashing?

20. How can I find the day of the week given the date?

21. Will 2000 be a leap year?

22. How do you write a program which produces its own source code as

its output?

23. What is ``Duff's Device''?

24. When will the next Obfuscated C Code Contest be held? How can I

get a copy of previous winning entries?

25. What was the entry keyword mentioned in K&R1?

26. Where does the name ``C'' come from, anyway?

27. How do you pronounce ``char''?

28. Where can I get extra copies of this list?

C++ Interview Questions

  1. Is it possible to have Virtual Constructor? If yes, how?If not, Why not possible ?
    There is nothing like Virtual Constructor.
    The Constructor cant be virtual as the constructor is a code which is responsible for creating a instance of a class and it cant be delegated to any other object by virtual keyword means.
  2. What about Virtual Destructor?
    Yes there is a Virtual Destructor. A destructor can be virtual as it is possible as at runtime depending on the type of object baller is balling to , proper destructor will be called.
  3. What is Pure Virtual Function? Why and when it is used ?
    The abstract class whose pure virtual method has to be implemented by all the classes which derive on these. Otherwise it would result in a compilation error.
    This construct should be used when one wants to ensure that all the derived classes implement the method defined as pure virtual in base class.
  4. What is problem with Runtime type identification?
    The run time type identification comes at a cost of performance penalty. Compiler maintains the class.
  5. How Virtual functions call up is maintained?
    Through Look up tables added by the compile to every class image. This also leads to performance penalty.
  6. Can inline functions have a recursion?
    Syntax wise It is allowed. But then the function is no longer Inline. As the compiler will never know how deep the recursion is at compilation time.
  7. How do you link a C++ program to C functions?
    By using the extern "C" linkage specification around the C function declarations.
    Programmers should know about mangled function names and type-safe linkages. Then they should explain how the extern "C" linkage specification statement turns that feature off during compilation so that the linker properly links function calls to C functions.
  8. Explain the scope resolution operator?
    It permits a program to reference an identifier in the global scope that has been hidden by another identifier with the same name in the local scope.
  9. How many ways are there to initialize an int with a constant?
    1. int foo = 123;
    2. int bar(123);
  10. What is your reaction to this line of code? delete this;
    It is not a good programming Practice.
    A good programmer will insist that you should absolutely never use the statement if the class is to be used by other programmers and instantiated as static, extern, or automatic objects. That much should be obvious.
    The code has two built-in pitfalls. First, if it executes in a member function for an extern, static, or automatic object, the program will probably crash as soon as the delete statement executes. There is no portable way for an object to tell that it was instantiated on the heap, so the class cannot assert that its object is properly instantiated. Second, when an object commits suicide this way, the using program might not know about its demise. As far as the instantiating program is concerned, the object remains in scope and continues to exist even though the object did itself in. Subsequent dereferencing of the baller can and usually does lead to disaster. I think that the language rules should disallow the idiom, but that's another matter.
  11. What is the difference between a copy constructor and an overloaded assignment operator?
    A copy constructor constructs a new object by using the content of the argument object. An overloaded assignment operator assigns the contents of an existing object to another existing object of the same class.
  12. When should you use multiple inheritance?
    There are three acceptable answers:- "Never," "Rarely," and "When the problem domain cannot be accurately modeled any other way."
  13. Consider an Asset class, Building class, Vehicle class, and CompanyCar class. All company cars are vehicles. Some company cars are assets because the organizations own them. Others might be leased. Not all assets are vehicles. Money accounts are assets. Real estate holdings are assets. Some real estate holdings are buildings. Not all buildings are assets. Ad infinitum. When you diagram these relationships, it becomes apparent that multiple inheritance is a likely and intuitive way to model this common problem domain. The applicant should understand, however, that multiple inheritance, like a chainsaw, is a useful tool that has its perils, needs respect, and is best avoided except when nothing else will do.

  14. What is a virtual destructor?
    The simple answer is that a virtual destructor is one that is declared with the virtual attribute.
    The behavior of a virtual destructor is what is important. If you destroy an object through a baller or reference to a base class, and the base-class destructor is not virtual, the derived-class destructors are not executed, and the destruction might not be comple
  15. Can a constructor throw a exception? How to handle the error when the constructor fails?
    The constructor never throws a error.
  16. What are the debugging methods you use when came across a problem?
    Debugging with tools like :
  17. GDB, DBG, Forte, Visual Studio.

    Analyzing the Core dump.

    Using tusc to trace the last system call before crash.

    Putting Debug statements in the program source code.

  18. How the compilers arranges the various sections in the executable image?
    The executable had following sections:-
  19. Data Section (uninitialized data variable section, initialized data variable section )

    Code Section

    Remember that all static variables are allocated in the initialized variable section.

  20. Explain the ISA and HASA class relationships. How would you implement each in a class design?
    A specialized class "is" a specialization of another class and, therefore, has the ISA relationship with the other class.
    This relationship is best implemented by embedding an object of the Salary class in the Employee class.
  21. When is a template a better solution than a base class?
    When you are designing a generic class to contain or otherwise manage objects of other types, when the format and behavior of those other types are unimportant to their containment or management, and particularly when those other types are unknown (thus, the generality) to the designer of the container or manager class.
  22. What are the differences between a C++ struct and C++ class?
    The default member and base-class access specifies are different.
    This is one of the commonly misunderstood aspects of C++. Believe it or not, many programmers think that a C++ struct is just like a C struct, while a C++ class has inheritance, access specifies, member functions, overloaded operators, and so on. Actually, the C++ struct has all the features of the class. The only differences are that a struct defaults to public member access and public base-class inheritance, and a class defaults to the private access specified and private base-class inheritance.
  23. How do you know that your class needs a virtual destructor?
    If your class has at least one virtual function, you should make a destructor for this class virtual. This will allow you to delete a dynamic object through a baller to a base class object. If the destructor is non-virtual, then wrong destructor will be invoked during deletion of the dynamic object.
  24. What is the difference between new/delete and malloc/free?
    Malloc/free do not know about constructors and destructors. New and delete create and destroy objects, while malloc and free allocate and deallocate memory.
  25. What happens when a function throws an exception that was not specified by an exception specification for this function?
    Unexpected() is called, which, by default, will eventually trigger abort().
  26. Can you think of a situation where your program would crash without reaching the breakball, which you set at the beginning of main()?
    C++ allows for dynamic initialization of global variables before main() is invoked. It is possible that initialization of global will invoke some function. If this function crashes the crash will occur before main() is entered.
  27. What issue do auto_ptr objects address?
    If you use auto_ptr objects you would not have to be concerned with heap objects not being deleted even if the exception is thrown.
  28. Is there any problem with the following:
    char *a=NULL; char& p = *a;?
    The result is undefined. You should never do this. A reference must always refer to some object.
  29. Why do C++ compilers need name mangling?
    Name mangling is the rule according to which C++ changes function's name into function signature before passing that function to a linker. This is how the linker differentiates between different functions with the same name.
  30. Is there anything you can do in C++ that you cannot do in C?

No. There is nothing you can do in C++ that you cannot do in C. After all you can write a C++ compiler in C

  • What are the major differences between C and C++?
    • What are the differences between new and malloc?
    • What is the difference between delete and delete[]?
    • What are the differences between a struct in C and in C++?
    • What are the advantages/disadvantages of using #define?
    • What are the advantages/disadvantages of using inline and const?
  • What is the difference between a baller and a reference?
    • When would you use a baller? A reference?
    • What does it mean to take the address of a reference?
  • What does it mean to declare a function or variable as static?
  • What is the order of initalization for data?
  • What is name mangling/name decoration?
    • What kind of problems does name mangling cause?
    • How do you work around them?
  • What is a class?
    • What are the differences between a struct and a class in C++?
    • What is the difference between public, private, and protected access?
    • For class CFoo { }; what default methods will the compiler generate for you>?
    • How can you force the compiler to not generate them?
    • What is the purpose of a constructor? Destructor?
    • What is a constructor initializer list?
    • When must you use a constructor initializer list?
    • What is a:
      • Constructor?
      • Destructor?
      • Default constructor?
      • Copy constructor?
      • Conversion constructor?
    • What does it mean to declare a...
      • member function as virtual?
      • member function as static?
      • member function as static?
      • member variable as static?
      • destructor as static?
    • Can you explain the term "resource acquisition is initialization?"
    • What is a "pure virtual" member function?
    • What is the difference between public, private, and protected inheritance?
    • What is virtual inheritance?
    • What is placement


    • What is the difference between

operator new

and the



  • What is exception handling?
    • Explain what happens when an exception is thrown in C++.
    • What happens if an exception is not caught?
    • What happens if an exception is throws from an object's constructor?
    • What happens if an exception is throws from an object's destructor?
    • What are the costs and benefits of using exceptions?
    • When would you choose to return an error code rather than throw an exception?
  • What is a template?
  • What is partial specialization or template specialization?
  • How can you force instantiation of a template?
  • What is an iterator?
  • What is an algorithm (in terms of the STL/C++ standard library)?
  • What is


  • What is wrong with this statement?

std::auto_ptr ptr(new char[10]);

  • It is possible to build a C++ compiler on top of a C compiler. How would you do this?

Sources :
DEVFYI - Developer Resource - FYI

Click here to get Interview's Topic Index