C and C++ Interview Questions and Answers

C and C++ Interview Questions and Answers

Last updated on 23rd Sep 2020, Blog, Interview Question

About author

sharan ( (Sr Technical Project Manager, Capgemini ) )

She is Possessing 8+ Years Of Experience in C & C++. Her Passion lies in Developing Entrepreneurs & Activities. Also, Rendered her intelligence to the Enthusiastic JOB Seekers.

(5.0) | 14547 Ratings 801

C programming language

C is a computer programming language. That means that you can use C to create lists of instructions for a computer to follow. C is one of thousands of programming languages currently in use. C has been around for several decades and has won widespread acceptance because it gives programmers maximum control and efficiency. C is an easy language to learn. It is a bit more cryptic in its style than some other languages, but you get beyond that fairly quickly. C is what is called a compiled language. This means that once you write your C program, you must run it through a C compiler to turn your program into an executable that the computer can run (execute). The C program is the human-readable form, while the executable that comes out of the compiler is the machine-readable and executable form. 

C++ programming language

C++ is general-purpose object-oriented programming (OOP) language developed by Bjarne Stroustrup. Originally, C++ was called “C with classes,” as it had all the properties of the C language with the addition of user-defined data types called “classes.” It was renamed C++ in 1983. C++ is considered an intermediate-level language, as it includes both high and low-level language features.

Below we have listed the top 100 c and c++ interview questions & answers for fresher and  experienced candidates to clear the job interview. 

1.What is a pointer on pointer?

Ans:

It’s a pointer variable which can hold the address of another pointer variable. It de-refers twice to point to the data held by the designated pointer variable.

Eg:

  • int x = 5, *p=&x, **q=&p;
  • Therefore ‘x’ can be accessed by **q.

2.Distinguish between malloc() & calloc() memory allocation.

Ans:

Both allocates memory from heap area/dynamic memory. By default calloc fills the allocated memory with 0’s.

3.What is keyword auto for?

Ans:

By default every local variable of the function is automatic (auto). In the below function both the variables ‘i’ and ‘j’ are automatic variables.

  • void f() {
  • int i;
  • auto int j;}

4.What are the valid places for the keyword break to appear.

Ans:

Break can appear only within the looping control and switch statement. The purpose of the break is to bring the control out from the said blocks.

5.Explain the syntax of for loop.

Ans:

  • for(expression-1;expression-2;expression-3) {
  • //set of statements
  • }

When control reaches for expression-1 is executed first. Then following expression-2, and if expression-2 evaluates to non-zero ‘set of statements’ and expression-3 is executed, follows expression-2.

6.What is difference between including the header file with-in angular braces < > and double quotes “ “

Ans:

If a header file is included within < > then the compiler searches for the particular header file only within the built in include path. If a header file is included within “ “, then the compiler searches for the particular header file first in the current working directory, if not found then in the built in include path.

7.How a negative integer is stored.

Ans:

Get the two’s compliment of the same positive integer. Eg: 1011 (-5)

Step-1 − One’s complement of 5 : 1010

Step-2 − Add 1 to above, giving 1011, which is -5

8.What is a static variable?

Ans:

A static local variable retains its value between the function call and the default value is 0. The following function will print 1 2 3 if called thrice.

  • void f() {
  • static int i; 
  • ++i; 
  • printf(“%d “,i);
  • }


If a global variable is static then its visibility is limited to the same source code.

9.What is a NULL pointer?

Ans:

A pointer pointing to nothing is called so. Eg: char *p=NULL;

10.What is the purpose of the extern storage specifier?

Ans:

  Used to resolve the scope of global symbols.
  Eg:  

  • main() {
  • extern int i;
  • Printf(“%d”,i);
  • }
  • int i = 20;
Subscribe For Free Demo

Error: Contact form not found.

11.Explain the purpose of the function sprintf().

Ans:

Prints the formatted output onto the character array.

12.What is the meaning of the base address of the array?

Ans:

The starting address of the array is called the base address of the array.

13.When should we use the register storage specifier?

Ans:

If a variable is used most frequently then it should be declared using register storage specifier, then possibly the compiler gives CPU register for its storage to speed up the lookup of the variable.

S++ or S = S+1, which can be recommended to increment the value by 1 and why?

S++, as it is single machine instruction (INC) internally.

14.What is a dangling pointer?

Ans:

A pointer initially holds a valid address, but later the held address is released or freed. Such a pointer is called a dangling pointer.

15.What is the purpose of the keyword typedef?

Ans:

It is used to alias the existing type. Also used to simplify the complex declaration of the type.

16.What is lvalue and rvalue?

Ans:

The expression appearing on the right side of the assignment operator is called an rvalue. Rvalue is assigned to lvalue, which appears on the left side of the assignment operator. The lvalue should designate a variable not a constant.

17.What is the difference between actual and formal parameters?

Ans:

The parameters sent to the function at the calling end are called as actual parameters while at the receiving of the function definition are called as formal parameters.

18.Can a program be compiled without the main() function?

Ans:

Yes, it can be but cannot be executed, as the execution requires main() function definition. 

19.What is the full form of OOPS?

Ans:

Object Oriented Programming System.

20.What is a class?

Ans:

Class is a blueprint which reflects the entities attributes and actions. Technically defining a class is designing an user defined data type.

21.What is an object?

Ans:

An instance of the class is called an object.

22.List the types of inheritance supported in C++.

Ans:

Single, Multilevel, Multiple, Hierarchical and Hybrid.

23.What is the role of protected access specifier?

Ans:

If a class member is protected then it is accessible in the inherited class. However, outside the both the private and protected members are not accessible.

24.What is encapsulation?

Ans:

The process of binding the data and the functions acting on the data together in an entity (class) called as encapsulation.

25.What is abstraction?

Ans:

Abstraction refers to hiding the internal implementation and exhibiting only the necessary details.

26.What is inheritance?

Ans:

Inheritance is the process of acquiring the properties of the existing class into the new class. The existing class is called a base/parent class and the inherited class is called a derived/child class.

27.Explain the purpose of the keyword volatile.

Ans:

Declaring a variable volatile directs the compiler that the variable can be changed externally. Hence avoiding compiler optimization on the variable reference.

28.What is an inline function?

Ans:

A function prefixed with the keyword inline before the function definition is called as inline function. The inline functions are faster in execution when compared to normal functions as the compiler treats inline functions as macros.

29.What is a storage class?

Ans:

Storage class specifies the life or scope of symbols such as variables or functions.

30.Mention the storage classes names in C++.

Ans:

The following are storage classes supported in C++

auto, static, extern, register and mutable

Course Curriculum

Best In-Depth Practical Oriented C & C++ Programming Training

  • Instructor-led Sessions
  • Real-life Case Studies
  • Assignments
Explore Curriculum

31.What is the role of mutable storage class specifier?

Ans:

A constant class object’s member variable can be altered by declaring it using a mutable storage class specifier. Applicable only for non-static and non-constant member variables of the class.

32.Distinguish between shallow copy and deep copy.

Ans:

Shallow copy does memory dumping bit-by-bit from one object to another. Deep copy is copying field by field from object to another. Deep copy is achieved using a copy constructor and or overloading assignment operator.

33.What is a pure virtual function?

Ans:

A virtual function with no function body and assigned with a value zero is called a pure virtual function.

34.What is an abstract class in C++?

Ans:

A class with at least one pure virtual function is called as abstract class. We cannot instantiate an abstract class.

35.What is a reference variable in C++?

Ans:

A reference variable is an alias name for the existing variable. Which means both the variable name and reference variable point to the same memory location. Therefore updation on the original variable can be achieved using the reference variable too.

36.What is the role of static keywords in class member variables?

Ans:

A static variable does exit through the objects for the respective class and are not created. Static member variables share a common memory across all the objects created for the respective class. A static member variable can be referred using the class name itself.

37.Explain the static member function.

Ans:

A static member function can be invoked using the class name as it exits before class objects come into existence. It can access only static members of the class.

38.Name the data type which can be used to store wide characters in C++.

Ans:

wchar_t

39.What are/is the operator/operators used to access the class members?

Ans:

Dot (.) and Arrow ( -> )

40.Can we initialize a class/structure member variable as soon as the same is defined?

Ans:

No, Defining a class/structure is just a type definition and will not allocate memory for the same.

41.What is the data type to store the Boolean value?

Ans:

boolean, is the new primitive data type introduced in C++ language.

42.What is function overloading?

Ans:

Defining several functions with the same name with a unique list of parameters is called function overloading.

43.What is operator overloading?

Ans:

Defining a new job for the existing operator with reference to  the class objects is called operator overloading.

44.Do we have a String primitive data type in C++?

Ans:

No, it’s a class from STL (Standard template library).

45.Name the default standard streams in C++.

Ans:

cin, cout, cerr and clog.

46.Which access specifier/s can help to achieve data hiding in C++?

Ans:

Private & Protected.

47.When a class member is defined outside the class, which operator can be used to associate the function definition to a particular class?

Ans:

Scope resolution operator (::)

48.What is a destructor? Can it be overloaded?

Ans:

A destructor is the member function of the class which is having the same name as the class name and prefixed with tilde (~) symbol. It gets executed automatically with reference to the object as soon as the object loses its scope. It cannot be overloaded and the only form is without the parameters.

49.What is a constructor?

Ans:

A constructor is the member function of the class which is having the same name as the class name and gets executed automatically as soon as the object for the respective class is created.

50.What is a default constructor? Can we provide one for our class?

Ans:

Every class does have a constructor provided by the compiler if the programmer doesn’t provide one and is known as default constructor. A programmer provided constructor with no parameters is called a default constructor. In such a case the compiler doesn’t provide the constructor.

Course Curriculum

Learn Industry Experts Curated C & C++ Certification Course

Weekday / Weekend BatchesSee Batch Details

51.Which operator can be used in C++ to allocate dynamic memory?

Ans:

‘new’ is the operator can be used for the same.

52.What is the purpose of the ‘delete’ operator?

Ans:

‘delete’ operator is used to release the dynamic memory which was created using ‘new’ operator.

53.Can I use the malloc() function of the C language to allocate dynamic memory in C++?

Ans:

Yes, as C is the subset of C++, we can use all the functions of C in C++ too.

54.Can I use the ‘delete’ operator to release the memory which was allocated using the malloc() function of the C language?

Ans:

No, we need to use free() of C language for the same.

55.What is a friend function?

Ans:

A function which is not a member of the class but still can access all the members of the class is called so. To make it happen we need to declare within the required class following the keyword ‘friend’.

56.What is a copy constructor?

Ans:

A copy constructor is the constructor which takes the same class object reference as the parameter. It gets automatically invoked as soon as the object is initialized with another object of the same class at the time of its creation.

57.Does C++ support exception handling? If so what are the keywords involved in achieving the same.

Ans:

C++ does support exception handling. try, catch & throw are keywords used for the same.

58.Explain the pointer – this.

Ans:

This is the pointer variable of the compiler which always holds the current active object’s address.

59.What is the difference between the keywords struct and class in C++?

Ans:

By default the members of struct are public and by default the members of the class are private.

60.Can we implement all the concepts of OOPS using the keyword struct?

Ans:

Yes.

61.What is the block scope variable in C++?

Ans:

A variable whose scope is applicable only within a block is said so. Also a variable in C++ can be declared anywhere within the block.

62.What is the role of the file opening mode ios::trunk?

Ans:

If the file already exists, its content will be truncated before opening the file.

63.What is the scope resolution operator?

Ans:

The scope resolution operator is used to

  • Resolve the scope of global variables.
  • To associate function definition to a class if the function is defined outside the class.

64.What is a namespace?

Ans:

A namespace is the logical division of the code which can be used to resolve the name conflict of the identifiers by placing them under different name space.

65.What are command line arguments?

Ans:

The arguments/parameters which are sent to the main() function while executing from the command line/console are called so. All the arguments sent are the strings only.

66.What are the key features in the C programming language?

Ans:

Features are as follows:

  • Portability: It is a platform-independent language.
  • Modularity: Possibility to break down large programs into small modules.
  • Flexibility: The possibility of a programmer to control the language.
  • Speed: C comes with support for system programming and hence it compiles and executes with high speed when compared with other high-level languages.
  • Extensibility: Possibility to add new features by the programmer.

67.What is the description for syntax errors?

Ans:

The mistakes/errors that occur while creating a program are called syntax errors. Misspelled commands or incorrect case commands, an incorrect number of parameters in calling method /function, data type mismatches can be identified as common examples for syntax errors.

68.What is the process to create an increment and decrement statement in C?

Ans:

There are two possible methods to perform this task.

  • Use increment (++) and decrement (-) operator.

Example

When x=4, x++ returns 5 and x- returns 3.

  • Use conventional + or – signs.

Example

When x=4, use x+1 to get 5 and x-1 to get 3.

69.What is the difference between abs() and fabs() functions?

Ans:

Both functions are to retrieve absolute value. abs() is for integer values and fabs() is for floating type numbers. Prototype for abs() is under the library file < stdlib.h > and fabs() is under < math.h >.

70.Describe Wild Pointers in C?

Ans:

Uninitialized pointers in the C code are known as Wild Pointers. They point to some arbitrary memory location and can cause bad program behavior or program crash.

C and C++ Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

71.What is the difference between ++a and a++?

Ans:

‘++a”  is called prefixed increment and the increment will happen first on a variable. ‘a + +’ is called postfix increment and the increment happens after the value of a variable used for the operations.

72.Describe the difference between = and == symbols in C programming?

Ans:

‘==’ is the comparison operator which is used to compare the value or expression on the left-hand side with the value or expression on the right-hand side.

‘=’ is the assignment operator which is used to assign the value of the right-hand side to the variable on the left-hand side.

73.What is the explanation for the prototype function in C?

Ans:

Prototype function is a declaration of a function with the following information to the compiler.

  • Name of the function.
  • The return type of the function.
  • Parameters list of the function.
integer-parameters

In this example Name of the function is Sum, the return type is the integer data type and it accepts two integer parameters.

74.What is the explanation for the cyclic nature of data types in C?

Ans:

Some of the data types in C have special characteristic nature when a developer assigns value beyond the range of the data type. There will be no compiler error and the value changes according to a cyclic order. This is called cyclic nature. Char, int, long int data types have this property. Further float, double and long double data types do not have this property.

75.Describe the header file and its usage in C programming?

Ans:

The file containing the definitions and prototypes of the functions being used in the program are called a header file. It is also known as a library file.

Example:

The header file contains commands like printf and scanf is from the stdio.h library file.

76.There is a practice in coding to keep some code blocks in comment symbols than delete it when debugging. How does this affect debugging?

Ans:

This concept is called commenting out and this is the way to isolate some part of the code which scans possible reasons for the error. Also, this concept helps to save time because if the code is not the reason for the issue it can simply be removed from comment.

77.What are the general descriptions for loop statements and available loop types in C?

Ans:

A statement that allows the execution of statements or groups of statements in a repeated way is defined as a loop.

The following diagram explains a general form of a loop.

nested-loop

There are 4 types of loop statements in C.

  • While loop
  • For Loop
  • Do…While Loop
  • Nested Loop

78.What is a nested loop?

Ans:

A loop that runs within another loop is referred to as a nested loop. The first loop is called the Outer Loop and the inside loop is called the Inner Loop. The inner loop executes the number of times defined in an outer loop.

79.What is the behavioral difference when the header file is included in double-quotes (“”) and angular braces (<>)?

Ans:

When the Header file is included within double quotes (“ ”), compiler search first in the working directory for the particular header file. If not found, then it searches the file in the include path. But when the Header file is included within angular braces (<>), the compiler only searches in the working directory for the particular header file.

80.What is a sequential access file?

Ans:

General programs store data into files and retrieve existing data from files. With the sequential access file, such data are saved in a sequential pattern. When retrieving data from such files each data is read one by one until the required information is found.

81.What is the method to save data in a stack data structure type?

Ans:

Data is stored in the Stack data structure type using the First In Last Out (FILO) mechanism. Only the top of the stack is accessible at a given instance. Storing mechanism is referred to as a PUSH and retrieve is referred to as a POP.

82.What is the significance of C program algorithms?

Ans:

The algorithm is created first and it contains step by step guidelines on how the solution should be. Also, it contains the steps to consider and the required calculations/operations within the program.

83.How many ways are there to initialize an int with a Constant?

Ans:

There are two ways:

  • The first format uses traditional C notation.
    int result = 10;
  • The second format uses the constructor notation.
    int result (10);

84.What is a Constant? Explain with an example.

Ans:

A constant is an expression that has a fixed value. They can be divided into integer, decimal, floating-point, character or string constants depending on their data type.

Apart from the decimal, C++ also supports two more constants i.e. octal (to the base 8) and hexadecimal (to the base 16) constants.

Examples of Constants:

  • 75 //integer (decimal)
  • 0113 //octal
  • 0x4b //hexadecimal
  • 3.142 //floating point
  • ‘c’ //character constant
  • “Hello, World” //string constant

85.What are the various Arithmetic Operators in C++?

Ans:

C++ supports the following arithmetic operators:

  • + addition
  • – subtraction
  • * multiplication
  • / division
  • % module

86.What are the various Compound Assignment Operators in C++?

Ans:

Following are the Compound assignment operators in C++:

+=, -=, *=, /=, %=, >>=, <<=, &=, ^=,|=

Compound assignation operator is one of the most  important features of C++ language which allow us to change the value of a variable with one of the basic operators:

Example:

  • value += increase; is equivalent to value = value + increase;
  • if base_salary is a variable of type int.
  • int base_salary = 1000;
  • base_salary += 1000; #base_salary = base_salary + 1000
  • base_salary *= 5; #base_salary = base_salary * 5;

87.What are the Extraction and Insertion operators in C++? Explain with examples.

Ans:

In the iostream.h library of C++, cin, and cout are the two data streams that are used for input and output respectively. Cout is normally directed to the screen and cin is assigned to the keyboard.

“cin” (extraction operator): By using overloaded operator >> with cin stream, C++ handles the standard input.

  • int age;
  • cin>>age;

As shown in the above example, an integer variable ‘age’ is declared and then it waits for cin (keyboard) to enter the data. “cin” processes the input only when the RETURN key is pressed.

“cout” (insertion operator): This is used in conjunction with the overloaded << operator. It directs the data that followed it into the cout stream.

Example:

  • void myfunc()
  • {                         
  • Cout<<”Hello,This is my function!!”;
  • }
  • int main()
  • {
  • myfunc();
  • return 0;
  • }

88.What is the difference between while and do while loop? Explain with examples.

Ans:

The format of while loop in C++ is:

  • While (expression)
  • {
  • statements;
  • }

The statement block under while is executed as long as the condition in the given expression is true.

Example:

  • #include <iostream.h> 
  • int main()
  • {               
  • int n;               
  • cout<<”Enter the number : “;               
  • cin>>n;              
  • while(n>0)             
  • {                             
  •  cout<<” “<<n;                             
  •  –n;             
  •  }             
  •  cout<<”While loop complete”; 
  • }

In the above code, the loop will directly exit if n is 0. Thus in the while loop, the terminating condition is at the beginning of the loop and if it’s fulfilled, no iterations of the loop are executed.

Next, we consider the do-while loop.

The general format of do-while is:

  • do
  • {
  • statement;
  • }
  • while(condition);

Example:

  • #include<iostream.h>
  • int main()
  • {               
  • int n;              
  •  cout<<”Enter the number : “;               
  • cin>>n;               
  • do
  • {                          
  • cout<<n<<”,”;                        
  •   –n;                    
  •  }
  • while(n>0);                   
  •  cout<<”do-while complete”;
  • }

In the above code, we can see that the statement inside the loop is executed at least once as the loop condition is at the end. These are the main differences between the while and do-while.

In case of the while loop, we can directly exit the loop at the beginning, if the condition is not met whereas in the do-while loop we execute the loop statements at least once.

89.What do you mean by ‘void’ return type?

Ans:

All functions should return a value as per the general syntax.

However, in case, if we don’t want a function to return any value, we use “void” to indicate that. This means that we use “void” to indicate that the function has no return value or it returns “void”.

Example:

  • void myfunc()
  • {                        
  •  Cout<<”Hello,This is my function!!”;
  • }
  • int main()
  • {
  • myfunc();
  • return 0;
  • }

90.Explain Pass by Value and Pass by Reference.

Ans:

While passing parameters to the function using “Pass by Value”, we pass a copy of the parameters to the function.

Hence, whatever modifications are made to the parameters in the called function are not passed back to the calling function. Thus the variables in the calling function remain unchanged.

Example:

  • void printFunc(int a,int b,int c)
  • {                  
  • a *=2;                  
  • b *=2;                  
  • c *=2;
  • int main() 
  • {                 
  •  int x = 1,y=3,z=4;                 
  • printFunc(x,y,z);                
  •  cout<<”x = “<<x<<”\ny = “<<y<<”\nz = “<<z;
  • }

Output:

  • x=1
  • y=3
  • z=4

As seen above, although the parameters were changed in the called function, their values were not reflected in the calling function as they were passed by value.

However, if we want to get the changed values from the function back to the calling function, then we use the “Pass by Reference” technique.

To demonstrate this we modify the above program as follows:

  • void printFunc(int& a,int& b,int& c)
  • {                            
  • a *=2;                             
  • b *=2;                              
  • c *=2;
  •  int main()
  • {                  
  • int x =1,y=3,z=4;                  
  • printFunc(x,y,z);                   
  • cout<<”x = “<<x<<”\ny = “<<y<<”\nz = “<<z;
  • }

Output:

  • x=2
  • y=6
  • z=8

As shown above, the modifications done to the parameters in the called functions are passed to the calling function when we use the “Pass by reference” technique. This is because using this technique we do not pass a copy of the parameters but we actually pass the variable’s reference itself.

91.What are Default Parameters? How are they evaluated in the C++ function?

Ans:

Default Parameter is a value that is assigned to each parameter while declaring a function.

This value is used if that parameter is left blank while calling to the function. To specify a default value for a particular parameter, we simply assign a value to the parameter in the function declaration.

If the value is not passed for this parameter during the function call, then the compiler uses the default value provided. If a value is specified, then this default value is stepped on and the passed value is used.

Example:

  • int multiply(int a, int b=2)
  • {              
  • int r;             
  •  r = a * b;              
  • return r;
  •  int main() 
  • {               
  • Cout<<multiply(6);            
  • Cout<<”\n”;            
  • Cout<<multiply(2,3); 
  • }

Output:

  • 12
  • 6

As shown in the above code, there are two calls to multiply functions. In the first call, only one parameter is passed with a value. In this case, the second parameter is the default value provided. But in the second call, as both the parameter values are passed, the default value is overridden and the passed value is used.

92.What is an Inline function in C++?

Ans:

Inline function is a function that is compiled by the compiler as the point of calling the function and the code is substituted at that point. This makes compiling faster. This function is defined by prefixing the function prototype with the keyword “inline”.

Such functions are advantageous only when the code of the inline function is small and simple. Although a function is defined as Inline, it is completely compiler dependent to evaluate it as inline or not.

93.Why are arrays usually processed with for loops?

Ans:

Array uses the index to traverse each of its elements.

If A is an array then each of its elements is accessed as A[i]. Programmatically, all that is required for this to work is an iterative block with a loop variable i that serves as an index (counter) incrementing from 0 to A.length-1.

This is exactly what a loop does and this is the reason why we process arrays using for loops.

94.State the difference between delete and delete[].

Ans:

“delete[]” is used to release the memory allocated to an array which was allocated using new[]. “delete” is used to release one chunk of memory which was allocated using new.

95.What is wrong with this code?

Ans:

  • T *p = new T[10];
  • delete p;

Ans: The above code is syntactically correct and will compile fine.

The only problem is that it will just delete the first element of the array. Though the entire array is deleted, only the destructor of the first element will be called and the memory for the first element is released.

96.What’s the order in which the objects in an array are destroyed?

Ans:

Objects in an array are destructed in the reverse order of construction: First constructed, last destroyed.

Example,

the order for destructors will be a[9], a[8], …, a[1], a[0]:

  • voiduserCode()
  • {                 
  • Car a[10];                 
  •  …
  • }

97.What is a Storage Class? Mention the Storage Classes in C++.

Ans:

Storage class determines the life or scope of symbols such as variables or functions.

C++ supports the following storage classes:

  • Auto
  • Static
  • Extern
  • Register
  • Mutable

98.Explain Mutable Storage class specifier.

Ans:

The variable of a constant class object’s member cannot be changed. However, by declaring the variables as “mutable”, we can change the values of these variables.

99.What is the keyword auto for?

Ans:

By default, every local variable of the function is automatic i.e. auto. In the below function both the variables ‘i’ and ‘j’ are automatic variables.

  • void f() 
  • int i; auto
  • int j; 
  • }

Are you looking training with Right Jobs?

Contact Us

Popular Courses