C and C++ Interview Questions with Answers
C and C++ Interview Questions |
Q1: When is a switch statement better than multiple if statements?
Answer: A switch statement is generally best to use when you have more than two conditional expressions based on a single variable of numeric type.
Q2: What is the return type of printf library function?
Answer: printf functions have int return type which is used to return number of elements which is printed
Q3: What is dangling pointer?
Answer: Dangling pointer is referred to that pointer which points to deallocated memory
location.
Q4: How can we achieve run time polymorphism in C++?
Answer: We can achieve run time polymorphism with the use of virtual function in base class and overriding same function in derived class in C++. And base’s pointer pointing to object of base or derived class, that class’s function will be called.
Q5: Library function which is used to convert string value into int value?
Answer: atoi () , the function is defined in header file is stdlib.h
Q6: How the overriding is different than overloading?
Answer: Overriding is achieved using redefine the base class into derived class’s function but overloading is achieved using two or more functions with same name and different arguments in context of type and number within same class or program scope.
Q7: Explain diamond problem of inheritance?
Answer: Diamond problem is ambiguity problem of hybrid inheritance, this ambiguity can be resolved using virtual base class while inheriting base class by multiple classes.
Q8: What is the significance of argc and argv in command line arguments ?
Answer: argc stands for number of arguments including executable file name, argv stands for argument vector(set of input strings).
Q9: Can we call any class member function without using object of the class
Answer: Yes, we can call static member function without using object. Static member function can be executed with the help of class itself.
Q10: Give uses of scope resolution operator ( :: ) in C++
Answer: 1) to define member function of the outside the class 2)to define static data member outside the class 3) to access static member function with classname 4) to access global variable
Q11: What is importance of this pointer?
Answer: this object always refers to self object which is used to access data member as well as this object is used to return self object from the member function.
Q12: Write the statements which are used to swap two variables without using 3rd variable and without using airthematic operators.
Answer: a=a^b; b=a^b; a=a^b;
Q13: Explain the polymorphism?
Answer: Polymorphism is the property of C++ , by which we can use same name
functions/operators with different purposes. Compile time polymorphism (functions
overloading, operator overloading) run time polymorphism (virtual function).
Q14: How type conversion is different than type casting ?
Answer: Generally type casting works with basic data types like int to float or vice versa, Type casting method is not applicable with user defined data types, so type conversion method is used with user defined data types conversion(like basic to user defined, user defined to basic and user defined 1 to user defined 2)
Q15: List the operators which can’t be overloaded ?
Answer: 1) :: 2) .* 3). 4)sizeof 5) ?:
Q16: Which operator can replace the if statement in the program?
Answer: conditional operator ( ?:)
Q17: What is the role of abstract class in c++?
Answer: Abstract class is the class which has minimum one pure virtual function inside its
definition. We cannot instantiate Abstract class.
Q18: What is the return type of malloc and calloc function and in which header file they are defined?
Answer: return type of memory functions are generic pointer(Void *) and they are defined in stdlib.h header file
Q19: What is the output of printf("%d")?
Answer: When we write printf("%d",x); this means compiler will print the value of x. But as here, there is nothing after %d so compiler will show in output window garbage value.
Q20: What is the difference between "calloc(...)" and "malloc(...)"?
Answer: calloc(...) allocates a block of memory for an array of elements of a certain size. By default the block is initialized to 0. The total number of memory allocated will
be (number_of_elements * size).malloc(...) takes in only a single argument which is the
memory required in bytes. malloc(...) allocated bytes of memory and not blocks of memory like calloc(...).
Q21: What is the difference between "printf(...)" and "sprintf(...)"?
Answer: sprintf(...) writes data to the character array whereas printf(...) writes data to the standard output device.
Q22: What is the difference between namespace and assembly?
Ans. Namespace is a collection of different classes whereas an assembly is the basic building blocks of the .net framework.
Q23: What is the difference between early binding and late binding?
Ans. Calling a non-virtual method, decided at a compile time is known as early binding. Calling a virtual method (Pure Polymorphism), decided at a runtime is known as late binding.
Q24: What is the difference between strings and character arrays?
Answer: A major difference is: string will have static storage duration, whereas as a character array will not, unless it is explicitly specified by using the static keyword.
Q25: What is the difference between const char* p and char const* p?
Answer: In const char* p, the character pointed by ‘p’ is constant, so u cant change the value of character pointed by p but u can make ‘p’ refer to some other location.
In char const* p, the ptr ‘p’ is constant not the character referenced by it, so u cant make ‘p’ to reference to any other location but u can change the value of the char pointed by ‘p’.
Q26: Can static variables be declared in a header file?
Answer: You can’t declare a static variable without defining it as well (this is because the
storage class modifiers static and extern are mutually exclusive). A static variable can be
defined in a header file, but this would cause each source file that includes the header file to have its own private copy of the variable, which is probably not what was intended.
Q27: What is a null pointer?
Answer: There are times when it’s necessary to have a pointer that doesn’t point to anything.The macro NULL, defined in , has a value that’s guaranteed to be different from any valid pointer. NULL is a literal zero, possibly cast to void* or char*. Some people, notably C++ programmers, prefer to use 0 rather than NULL.
The null pointer is used in three ways:
1) To stop indirection in a recursive data structure
2) As an error value
Q28: What is the difference between text and binary modes of reading and writing files to disk?
Answer: Streams can be classified into two types: text streams and binary streams. Text
streams are interpreted, with a maximum length of 255 characters. With text streams, carriage return/line feed combinations are translated to the newline n character and vice versa. Binary streams are uninterrupted and are treated one byte at a time with no translation of characters.Typically, a text stream would be used for reading and writing standard text files, printing output to the screen or printer, or receiving input from the keyboard.
A binary text stream would typically be used for reading and writing binary files such as
graphics or word processing documents, reading mouse input, or reading and writing to the modem.
Q29: What is static memory allocation and dynamic memory allocation?
Answer: Static memory allocation: The compiler allocates the required memory space for a declared variable.By using the address of operator, the reserved address is obtained and this address may be assigned to a pointer variable.Since most of the declared variable have static memory,this way of assigning pointer value to a pointer variable is known as static memory allocation. Memory is assigned during compilation time.
Q30: How are pointer variables initialized?
Answer: Pointer variable are initialized by one of the following two ways
- Static memory allocation
- Dynamic memory allocation
Q31: What is the difference between arrays and pointers?
Answer: Pointers are used to manipulate data using the address. Pointers use * operator to access the data pointed to by them
- Arrays use subscripted variables to access and manipulate data. Array variables can be
equivalently written using pointer expression.
Q32: Is using exit() the same as using return?
Answer: No. The exit() function is used to exit your program and return control to the operating system. The return statement is used to return from a function and return control to the calling function. If you issue a return from the main() function, you are essentially returning control to the calling function, which is the operating system. In this case, the return statement and exit() function are similar.
Q33: What is indirection?
Answer: If you declare a variable, its name is a direct reference to its value. If you have a pointer to a variable or any other object in memory, you have an indirect reference to its value.
Q34: What is modular programming?
Answer: If a program is large, it is subdivided into a number of smaller programs that are
called modules or subprograms. If a complex problem is solved using more modules, this
approach is known as modular programming.
Q35: What is an lvalue?
Answer: An lvalue is an expression to which a value can be assigned. The lvalue expression is located on the left side of an assignment statement, whereas an rvalue is located on the right side of an assignment statement. Each assignment statement must have an lvalue and an rvalue. The lvalue expression must reference a storable variable in memory. It cannot be a constant.
Q36: Differentiate between an internal static and external static variable?
Answer: An internal static variable is declared inside a block with static storage class whereas an external static variable is declared outside all the blocks in a file.An internal static variable has persistent storage, block scope and no linkage.An external static variable has permanent storage,file scope and internal linkage.
Q37: What is a void pointer?
Answer: A void pointer is a C convention for a raw address. The compiler has no idea what
type of object a void Pointer really points to. If you write int *ip; ip points to an int. If you write
void *p; p doesn’t point to a void!
Q38: When should a type cast not be used?
Answer: A type cast should not be used to override a const or volatile declaration. Overriding these type modifiers can cause the program to fail to run correctly. A type cast should not be used to turn a pointer to one type of structure or data type into another. In the rare events in which this action is beneficial, using a union to hold the values makes the programmer’s intentions clearer.
Q39: What is a static function?
Answer: A static function is a function whose scope is limited to the current source file. Scope refers to the visibility of a function or variable. If the function or variable is visible outside of the current source file, it is said to have global, or external, scope. If the function or variable is not visible outside of the current source file, it is said to have local, or static, scope.
Q40: Differentiate between a linker and linkage?
Answer: A linker converts an object code into an executable code by linking together the
necessary build in functions. The form and place of declaration where the variable is declared in a program determine the linkage of variable.
Q41: What is the difference between declaration and definition?
Answer: The declaration tells the compiler that at some later point we plan to present the definition of this declaration. The definition contains the actual implementation.
Q42: What are the advantages of inheritance?
Answer: 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.
Q43: What are inline functions and when they can prove beneficial?
Answer: inline functions are used 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
Q44: What are templates in C++?
Answer: Templates allow creating generic functions that admit any data type as parameters and return value without having to overload the function with all the possible data types.
Q45: What keyword will you use when defining a function in base class to allow this function to be a polymorphic function?
Answer: virtual
Q46: Why are arrays usually processed with for loop?
Answer: The real power of arrays comes from their facility of using an index variable to
traverse the array, accessing each element with the same expression a[i]. All there is need to make this work is a iterated statement in which the variable i serves as a counter, incrementing from 0 to a.length -1That is exactly what a loop does.
Q47: What is the difference between macro and inline?
Answer: Inline follows strict parameter type checking, macros do not. Macros are always
expanded by preprocessor, whereas compiler may or may not replace the inline definitions.
Q48: How can we access protected and private members of a class?
Answer: In the case of members protected and private, these could not be accessed from
outside the same class at which they are declared. This rule can be transgressed with the use of the friend keyword in a class, so we can allow an external function to gain access to the protected and private members of a class.
Q49: In the derived class, which data members of the base class are visible?
Answer: In the public and protected sections.
Q50: What is the need for a Virtual Destructor?
Answer: Destructors are declared as virtual because if do not declare it as virtual the base
class destructor will be called before the derived class destructor and that will lead to memory leak because derived class’s objects will not get freed. Destructors are declared virtual so as to bind objects to the methods at runtime so that appropriate destructor is called.
Q51: What is the Standard Template Library (STL)?
Answer: A library of container templates approved by the ANSI committee for inclusion in the standard C++ specification. A programmer who then launches into a discussion of the generic programming model, iterators, allocators, algorithms, and such, has a higher than average understanding of the new technology that STL brings to C++ programming.
Q52: What is difference between Class and Structure in C++?
Answer: In class data members are private but in structure they are public by default.
Q53: Why we create NULL pointers?
Answer: So that pointer should not point to any random address.
Q54: Why do we use file handling?
Answer: To store data permanently.
Q55: Which function is used to position back from the end of file object?
Answer: seekg()
Q56: What is a stream?
Answer: A stream is a continuous series of bytes that flow into or out of your program. Input and output from devices such as the mouse, keyboard, disk, screen, modem, and printer are all handled with streams.
Q57: What is the difference between realloc() and free()?
Answer: 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.
Q58: Can Constructor of class be private?
Answer: We won’t make object somewhere else in code outside class. So no fun of making it private.
Q59: Can local and global variables be same names?
Answer: Yes; global variable access with scope resolution operator i.e. ::variablename
Q60: What type of functions are nonmember functions of a class but are granted the same privileges as methods of the class.
Answer: Friend Functions
Q61: The constructor that performs an initialization using another object of the same class is called as?
Answer: Copy Constructor
Q62: In C++, Which keyword can you use with a variable so that when function is called by reference and still prevent the function from changing its value?
Answer: const
Q63: How many destructors can a class have?
Answer: 1
Q64: Out of fgets() and gets() which function is safe to use and why?
Answer: fgets() is safer than gets(), because we can specify a maximum input length. Neither one is completely safe, because the compiler can’t prove that programmer won’t overflow the buffer he pass to fgets ().
Q65: Why doesn’t this code: a[i] = i++; work?
Answer: The sub expression i++ causes a side effect .it modifies i’s value which leads to
undefined behavior since i is also referenced elsewhere in the same expression.
Q66: Are the expressions *ptr ++ and ++ *ptr same?
Answer: No,*ptr ++ increments pointer and not the value pointed by it. Whereas ++ *ptr
increments the value being pointed to by ptr.
Q67: What would be the equivalent pointer expression foe referring the same element as a[p][q][r][s] ?
Answer: *( * ( * ( * (a+p) + q ) + r ) + s)
Q68: Are the variables argc and argv are always local to main?
Answer: Yes they are local to main.
Q69: Can main () be called recursively?
Answer: Yes
Q70: How is a file closed?
Answer: A file is closed using fclose() function
Eg. fclose(fp); Where fp is a file pointer.
Q71: What is the purpose of ftell ?
Answer: The function ftell() is used to get the current file represented by the file pointer.
ftell(fp); returns a long integer value representing the current file position of the file pointed by the file pointer fp.If an error occurs ,-1 is returned.
Q72: Difference between an array of pointers and a pointer to an array?
Answer: Array of pointers
1- Declaration is: data_type *array_name[size];
2-Size represents the row size.
3- The space for columns may be dynamically
Pointers to an array
1-Declaration is data_type ( *array_name)[size];
2-Size represents the column size.
Q73: Can a Structure contain a Pointer to itself?
Answer: Yes such structures are called self-referential structures.
Q74: How many ways are there to initialize an int with a constant?
Answer: There are two formats for initializers in C++ as shown in the example that follows. The first format uses the traditional C notation. The second format uses constructor notation.
int foo = 123;
int bar (123);
Q75: Why shouldn't I start variable names with underscores?
Answer: Identifier names beginning with two underscores or an underscore followed by a
capital letter are reserved for use by the compiler or standard library functions wherever they appear.
Q76: Is a default case necessary in a switch statement?
Answer: No, but it is not a bad idea to put default statements in switch statements for error- or logic-checking purposes. For instance, the following switch statement is perfectly normal.
Q77: Can the last case of a switch statement skip including the break?
Answer: Even though the last case of a switch statement does not require a break statement at the end, you should add break statements to all cases of the switch statement, including the last case. You should do so primarily because your program has a strong chance of being maintained by someone other than you who might add cases but neglect to notice that the last case has no break statement.
Q78: Which bit wise operator is suitable for checking whether a particular bit is on or off?
Answer: The bitwise AND operator.
Q79: Can the sizeof operator be used to tell the size of an array passed to a function?
Answer: No. There's no way to tell, at runtime, how many elements are in an array parameter just by looking at the array parameter itself. Remember, passing an array to a function is exactly the same as passing a pointer to the first element. This is a Good Thing. It means that passing pointers and arrays to C functions is very efficient.
Q80: When should the register modifier be used? Does it really help?
Answer: The register modifier hints to the compiler that the variable will be heavily used and should be kept in the CPU's
Preparation material @ Placement Papers Hub
C and C++ Interview Questions with Answers
Reviewed by @NA
on
5:30:00 PM
Rating:
Hello.. your blog is great. I read your blog and like it very much. Thanks for sharing.
ReplyDeleteC++ Interview Questions and Answers
Thanks for that this it is so much banificial for us
ReplyDeleteReally helpful...
ReplyDelete