Top C/C++ Interview Questions in 2021: Part 2

Top C/C++ Interview Questions in 2021: Part 2
Top C/C++ Interview Questions in 2021: Part 2

Introduction 

Welcome to another Blog on Top C/C++ Interview questions. Programming questions asked in an interview are not difficult to answer if you have clearly understood the concepts. So this blog will help you out by resolving your doubts on C/C++, with the help of some programming questions and some eye-openers (so-called tricky ones) typically asked in Interviews. 

Before moving on, you may refer to Part 1 of this series which consists of 30 theoretical C/C++ interview questions.  

Programming C/C++ Interview Questions 

Q1) Find the output of the following C program fragment which is written in the main function:

char *p = "CODINGNINJAS2021";
char *c = p;
printf("%s", c + c[11] - c[5]);

Answer) Let’s observe the above code. The first line is a char pointer storing a contiguous sequence of characters of length 16.

In the code, c[11] = *(c+11), which is the address of the element at the 11th index. Since we cannot calculate the exact address but assume that the starting address is some arbitrary number, say 1000 here. (Note: you can start from any address of your choice)

The main thing to learn here is the address of the next element is:

current address + size of a char data type (i.e. 1 byte).

Hence the address calculated for each element w.r.t the starting element is shown in the figure. 

c: starting address or address of the first element.

c[n] : element at nth index.

blog banner 1

c + c[11] – c[5] = 1000 + ‘S’ – ‘G’ = 1000 + 83 – 71 = 1012

It’s the address for the element at the 12th index, and when we print it, 

It will dereference the pointer starting from the 12th index.

Hence, the output will be 2021.

Q2) Find the output of the following C program:

#include<stdio.h>
int f(){
static int count = 7;
return count--;
}
int main(void){
for(f();f();f()) 
    printf("%d", f());
}

Answer) This tests your knowledge of loops, static keyword. Understand the working of for loops by the following flow diagram:

Now follow the flow of the diagram and try to dry run it for a loop.

When you dry run, you will see there was 1 function call during the initialization block, 2 function calls during the Do something block, 2 function calls during the updation block, and 2 function calls in the condition block.

The important thing here is that the ‘count’ is a static variable and will keep on getting updated once it’s initialized for the first time.

So, the final output on the screen will be 52.

Q3) Find the output of the following C program:

#include<stdio.h>
int f(int n){
if(n==1) return 1;
int x = 1;
for(int i=1; i<n; ++i)
x+= (f(i) * f(n-i));
return x;
} 

Find the value of f(5).

Answer) The value of f(5) can be computed using the following recursion tree since we can see recursive calls made:

  1. f(1) = 1
  1. f(2) = 2 (Why?)

i=1,   x = x+f(1) * f(2-1) = 1+ 1*1 = 1+1 = 2

  1. f(3) = 5 (Why?)

i = 1, x = x + f(1) * f(3-1) = 1+1*2 = 1+2 = 3

i = 2, x = x + f(2) * f(3-2) = 3 + 2*1 = 3+2 = 5

  1. f(4) = 15 (Why?)

i=1, x = x + f(1) * f(4-1) = 1 + 1*5 = 1+ 5 = 6

i=2, x = x + f(2) * f(2) = 6 + 2 * 2 = 10

i=3, x = x + f(3) * f(1) = 10 + 5 * 1 = 15

  1. f(5) = 51(Why)?

i = 1, x = x + f(1) * f(5-1) = 1 + 1*15 = 1+ 15 = 16

i = 2, x = x + f(2) * f(5-2) = 16 + 2*5 = 16 + 10 = 26

i = 3, x = x + f(3) * f(5-3) = 26 + 5*2 = 26 + 10 = 36

i = 4, x = x + f(4) * f(5-4) = 36 + 15 * 1 = 36 + 15 = 51

Q4) Find the output of the following C++ program:

        #include<iostream>
using namespace std;
int main(){
int val = 1;
const int c = val;
const int *const pointer = &val;
*(pointer)++;
int d = 99;
pointer = &d;
}

If the program results in error, mention a single change that should be done to resolve the error?

Answer) The first thing is that any constant object cannot be modified, so the statement *(pointer)++ will show an error as it tries to increment the value pointed by the constant pointer. Again there is also reassignment of a constant object to another variable which is not allowed. We can resolve the error by removing the const keyword from “const int *const pointer = &val;”.

Q5) What is the output of the following C program?

#include<stdio.h>

int main(void){

volatile int j=10;

int i=10;

printf(“%d %d %d %d\n”,++i,i++,i,i++);

printf(“%d %d %d %d\n”,++j,j++,j,j++);

}

Answer) 13 11 13 10

       13 11 11 10

The above two lines are printed on the screen.

To understand, one needs to understand the volatile keyword and compiler optimizations done with normal variables. 

Q6) What is the output of the following C++ program?

#include <bits/stdc++.h>
using namespace std;

int var = 0;
class First{
public:
    First(){
        std::cout << "1" ;
        if(var++ == 0){
            throw exception();
        }
    }    
    ~First(){cout<<"(1)";}
};
class Second{
public:
    Second(){cout<<"2";}
    ~Second(){cout<<"(2)";}
    First first;
};
void func(){static Second second;}
int main() {
try{
    func();
}catch(exception &){
    cout<<"3";
    func();
}
return 0;
}

Answer) The output will be 1312(2)(1)

First, it’ll go inside the main function’s try block and call function func(). It creates a static object of class Second. It will create an object of first-class by calling its constructor, which will be printed, and an exception will be raised, and then it’ll go in the catch block straightaway. 

Note, the value of ‘var’ is 1 now. Then again, the func() is called, and the first object is created, and then the constructor is called and thus 1 is printed. Then, the second class’s constructor is called, and 2 is printed. In the end, the destructors of the second and first class are called.

Q7) What is the output of the following C++ program?

#include <bits/stdc++.h>
using namespace std;
namespace C1{
    extern "C" int count;
}
namespace C2{
    extern "C" int count;
}
int C1::count = 0 ;
int main(){
    cout<<C2::count;
    C1::count = 1;
    cout<<C2::count;
}

Answer) You won’t understand the above question if you are not well aware of “extern” and namespaces keywords in C++. 

There are 2 namespaces with the same variables present outside the current source file. So, at first, the scope operators might confuse you that you are updating variables of two different namespaces, which is true. Still, the trick here is that both contain the same variable in an external C file, so ultimately the same variable is getting updated.

Hence the output will be 01.

Q8) What is the output of the following C program?

#include<stdio.h>
struct Point{
   int x=0;
   int y=0;
};
int main(){
   struct Point p1 = {1, 2};
 
   // p2 is a pointer to structure p1
   struct Point *p2 = &p1;
 
   // Accessing structure members using structure pointer
   printf("%d %d", p2->x, p2->y);
   return 0;
}

Answer) The above program will result in a compile-time error. The question requires having knowledge of structs in C.

So in a C structure, you can’t initialise the struct’s data members. 

This is because your structs itself is declaring a data type. 

(NOTE: From C++11, this feature was added.) 

If the line “ int x = 0; “ and “ int y = 0; “ are replaced by “int x, y;” the code will run fine and give the output 1 2.

Q9) Explain polymorphism using a sample program?

Answer) 

#include <bits/stdc++.h>
using namespace std;
class Shape{
public: 
    virtual void Draw() = 0; //abstract class with a pure virtual method
 };
 class Circle: public Shape{
public:                   
           int radius;
           void Draw() { 
printf("Drawn a Circle\n");
}
 };
class Square: public Shape{
    public: 
         int side;
         void Draw() { 
      printf("Drawn a Square\n");
 }
 };
 int main(){
                Shape *shape1;
                Shape *shape2;
                Circle c1;
                Square s1;
                shape1 = &c1;
                shape2 = &s1;
                shape1->Draw();
                shape2->Draw();
 }

Q10) Remove all occurrences of a character in the given string?

Answer) The approach for solving this question is quite simple. The aim is to remove a character given by the user from the input string. So what we can do is when we find the first character, which is the same as the given character, we will swap it with the next character in the input string (which is not the same as the given character). Now iterate from the index where the character has been swapped to and repeat the same process. Once the process is over, put ‘\0’ (NULL Character) at the end. Try out this problem Here.

Q11) Find out the output of the given C program:

#include<stdio.h>
int func(int n, int i){
if(n==0) return 0;
else if(n%2 == 0) return func(n/2 , 2*i) - i;
else return func(n/2, 2*i) + i;
}
int main(){
int ans= func(20, 1);
printf("%d", ans);
}

Answer)  The above code will test your knowledge of recursion. Let’s use the recursion stack and understand it.

The output on the screen would be 9.

Embedded C/C++ Interview Questions 

Q11) What do you mean by Embedded Systems?

Answer) An embedded system is a computer system based on microprocessors and integrated with software specifically designed to perform specific tasks and carry out real-time operations.

Q12) What is a Segmentation fault, and why is it caused?

Answer) Segmentation fault is a runtime error that crashes the execution of a program. It is caused because of several reasons.

It may be caused when we try to access nullptr or when the stack overflows, i.e., The amount of stack memory needed is greater than its maximum size available or while freeing a freed pointer.

Q13) What is the volatile keyword in C? Explain.

Answer) The volatile keyword is related to preventing objects declared as volatile from optimisations done by the compiler.

Any object declared as volatile is subject to an unexpected change in its value, i.e., its value could be changed abruptly by the compiler even if there is no change done on that object in the program.

Whenever an object is declared ‘volatile,’ its value is loaded from the memory registers rather than cache variables. 

It’s used when we create global variables to interrupt service routines and when working with multithreaded programs.

Q14) What is the difference between const and volatile in C?

(Commonly asked C/C++ Interview Questions)

Answer) When we talk about volatile objects in C, the object’s value is not in control of the compiler, and no optimisations are made by the compiler while compiling the program. So this leads to abrupt changes in its values, and thus it’s always referenced from the memory registers.

Whereas, once an object is declared as constant, we cannot change the value throughout the program’s lifetime. If we try to modify the object, it will throw a compilation error.

Example: Look at the following C program.

#include<stdio.h>
int main(void){
volatile int j=10;
int i=10;
printf("%d %d %d %d\n",++i,i++,i,i++);
printf("%d %d %d %d\n",++j,j++,j,j++);
}
Output: 13 11 13 10
     13 11 11 10

Look at the above example of how volatile makes a difference.

In the first print statement, optimisations are done by the compiler, and the result is printed. Whereas, in the second statement, the output is different because of non-optimisations of the compiler.

Q15) What is the difference between malloc() and calloc() in C?

Answer) The key differences between malloc() and calloc() are:

S.No.malloc()calloc()
1.A single memory block of memory of user-defined size is allocated.Multiple blocks of memory are assigned using the calloc() function.  
2.The memory allocated contains garbage values.The memory allocated contains 0.
3.Highly time-efficient.It’s time inefficient.
4.It’s not secure.It’s secure
5.The address of memory allocated doesn’t start from zero.The address of memory allocated starts from zero.

Q16) What is an ISR? 

Answer) An ISR is known as the Interrupt service routine. It’s an interrupt handler, which is triggered when an interrupt is encountered. So what happens when an interrupt is encountered?

Immediate response by the OS is to identify the type of the interrupt and call the corresponding subroutine for that particular interrupt. ISR doesn’t return anything. It contains a specific set of instructions to be performed, thus resolving the interrupt.

Q17) What is a NULL pointer? (Commonly asked C/C++ Interview Questions)

Answer) The NULL pointer is a particular type of pointer that doesn’t point to any memory locations. Earlier in C90, it was expressed as integer value 0 in a void pointer, but it clearly defined that it does not mean that it has any memory address as 0. Since it has no valid address, it can’t be dereferenced, and dereferencing it will result in a segmentation fault.

Any object assigned to a null pointer can be reassigned, but accessing a variable pointing to a null pointer isn’t allowed.

As a MACRO, a NULL pointer is present in many header files inside ‘stddef.h’, 

‘Mem.h’, etc.

Q18) What is an Interrupt Latency?

Answer) Latency means delay! So interrupt latency means the time elapsed between when an interrupt was encountered and when the Interrupt Service Routine serviced the interrupt.

Q19) What is the difference between RISC and CISC architectures?

Answer) The difference between RISC(reduced instruction set computer) and CISC(Complex instruction set computer) are:

Reduced Instruction Set Computer (RISC)Complex Instruction Set Computer (CISC)
This architecture has a smaller set of instructions.This architecture has a larger set of instructions.
Execution is faster.Execution is slower.
Complex Design.Simple Design.
They use separate hardware and memory units.They do not use separate Hardware and memory unit.

Q20) What is the difference between typedef and macro?

Answer) The main difference between typedef and macro is that typedef is a keyword used for defining a user-defined name for an existing data type. This is done because while defining certain objects, the data types are a bit complicated.

Example :    

typedef struct workers{
int id;
char *name;
   } employee;

Whereas a macro is a code fragment that a user-defined name can replace, and during compilation, it will be replaced by the original code fragment. 

Eye Openers

Q21) What will be the output of the following program when it’s run using a GCC compiler?

#include<stdio.h>
int main(){
  printf("%d ", sizeof(void));
  printf("%d ", sizeof(void *));
}

Answer) The program above is a compiler-specific program. The above program would compile on a GCC compiler, but it may not work if you try running the program on other C/C++ compilers.

The size of the void is considered to be 1 when we use GCC compilers.

The output of the program is 1 8.

Q22) What will be the output of the following program in C?

#include<stdio.h>
int main(){
int a[] = {5, 10};
int *q = a;
int *p = a+1;
int c = p - q;
printf("%d" , c);
}

Answer) The output of the program is 1.

To understand this, one should know about pointers and how addresses are manipulated. The pointer arithmetic is a bit different from ordinary arithmetic. A pointer points to the address of the memory locations, and when we talk about pointer subtraction, it gives the  (difference between the addresses)/(size of data type)

So, here we can say that c = (p-q)/4 = 4/4 = 1 

Note: The difference between 2 pointers of the same data type = 1. But if two pointers of different data types are subtracted, they’ll return a compile-time error.

Q23) What will be the output of the following C program?

#include<stdio.h>
int main(){
int a = 10;
a*=10+10;
printf("%d", a);
}

Answer) The answer you might be getting is 110, which is incorrect.

Note * has greater precedence than +, but when we use assignment operators, the RHS is evaluated first, and then the assignment operator comes into play. 

So correct answer is a = a *(10+10) = 200.

Q24) What will be the output of the following C program?

#include<stdio.h>
int main(){
int a, b, c;
b = (3+3, a = b, 1+7);
c = 3+3, 1+10;
printf("%d %d %d", a, b, c);
}

Answer) The answer is 2000101 8 6. This question tests your knowledge of the ‘,’ operator.

If we use the expression on RHS within brackets, then the last value is taken into account. Otherwise, it’s the first value.

Hence c gets the value 3+3 = 6.

B will get 1+7 = 8.

But a is getting a garbage value (Why?).

When we evaluate b = (3+3, a = b, 1+7), the evaluation is left to right so that so b will take the last value. But before b is assigned its value, a is assigned the value of b, which currently has a garbage value; hence a has a garbage value.

Note: if a=b were, at last, the value of b printed would have been a garbage value too.

Q25) What will be the output of the following C program?

#include<stdio.h>
int main(){
    float g = 0.375, a = 1.1;
    double b = 0.375, c = 1.1;
    if(g==b) printf("1");
    if(a==c) printf("2");
}

Answer) The output of the program is 1. You might be thinking that when 1.1 is the same as 1.1, then why 2 is not printed?

When we compare floats with doubles, only those float and double values terminating are equal; otherwise, they aren’t.

0.375 is a terminating decimal, but 1.1 is not.

Q26) What will be the output of the following C program?

#include<stdio.h>
int main(){
    int a=1, b=1;
    printf("%d", a+++++b);
}

Answer) The above program would throw a compile-time error because the compiler will not find the right or left values. 

Q27) What will be the output of the following C program?

#include<stdio.h>
int main(){
    int a=1, b=1;
    printf("%d", a+++ ++b);
}

Answer) The output is 3. The difference is that now the compiler can find one of the addends evaluated and then added to the other addend. So b is incremented, and since it’s the pre-increment operator, it will give 2 whereas a = 2, but because of the post-increment operator, it would give 1 as the second addend.

Q28) What will be the output of the following C program?

#include<stdio.h>
int main(){
    int *p = (int *)(malloc(20));
    printf("%d\n", sizeof(p));
}

Answer) The answer to the above program is 4. This question is generally asked by the interviewer to confuse the interviewee. So have strong basics to tackle these questions and get out of the interviewer’s trap. We know an integer pointer is 4 bytes. Thus ‘sizeof’ operator returns 4.

Q29) What will be the output of the following C program?

#include<stdio.h>
struct test{
int p:3;
int c:3;
int m:2;
};
int main(){
struct test s={2,-6,5};
printf("%d %d %d",s.p,s.c,s.m);
}

Answer) You must know about the “:” (colon) operator in C. The function of this operator is to take the specified number of bits from a given number. The number of bits to be taken is written after it.

It’s usually used in structs.

For example, int p:3;  means that whatever value is assigned to ‘p’, only 3 bits will be considered.

So, convert 2, -6, 5 in binary, i.e.0010, 1010, 0101, and now we have to take 3, 3, 2 bits, respectively.

s.p = 2(010), s.c = 2(010), s.m = 1(01).

Output is 2 2 1.

Q30) What will be the output of the following C program?

#include<stdio.h>
int main(){
int a=4;
int y = ++a + ++a + ++a;
printf("%d",y);
}

Answer) To understand the output of y = ++a + ++a + ++a; 

Understand what happens when ++a is written; value of a is incremented by 1 and then a is returned there.

Let’s see what would be the output of ++a + ++a first.

Update value a = 5, now when we have to update it the second time increment and return the value of a = 6 but now both sides have to be added i.e. a(6 now) + a(6 now) = 12.

Now update ‘a’ the third time; a = 7. Hence the output is 19

Frequently Asked Questions

What is scanf() in C?

scanf() is a method in the “stdio.h” library that can take input from the console.

Where to practice C/C++ questions?

You can go to CodeStudio and practice Questions based on C/C++. It’s a great resource that’ll help you get stronger in these languages.

Key TakeAways

Hey! You have covered some great content. We hope you have learned some new concepts and are ready to crack the interviews having C/C++ questions. 

Now, you may check out our course on Interview Preparation. It has a vast set of problems along with concepts that will help you to ace your interviews. So what are you waiting for?

Go and practice now!

Happy Learning!
By: Aniket Verma