Are you looking to get a discount on popular programming courses? Then click here. View offers

C and Interview Questions


Disclosure: Hackr.io is supported by its audience. When you purchase through links on our site, we may earn an affiliate commission.



Top 50 C Interview Questions and Answers in 2022

Posted in C, Interview Questions
C Interview Questions

Table of Contents

Despite being nearly 50 years old, C is still front and center in the programming scene. The language not only has a wide variety of applications, but is also the inspiration for a variety of modern, powerful programming languages, including Java, C#, and Python.

Although there are very few job profiles these days that only require a high level of proficiency in C, most programming jobs necessitate a good understanding of the fundamental concepts of the C programming language. 

These C Interview questions and answers cover many of those programming concepts and are a good way to prepare yourself for an interview that requires a good understanding of C.

Top C Interview Questions and Answers

C Basic Interview Questions

1. What are some of the most important features of C?

Some of the most important features of C are:

  • Extensibility: can adopt new features.
  • Fast: support for system programming allows faster compilation and execution compared to popular high-level languages like Java and Python.
  • Memory Management: comes with built-in memory management for saving memory and optimizing memory use.
  • Middle-Level Programming Language: can be used for system programming as well as application programming.
  • Platform independence/Portability: a C program written for one machine can run on other machines with little to no modification.
  • Simplicity: follows a structured approach. Facilitates breaking down a big, complex program into smaller, independent, and easy-to-manage modules (sub-programs).

2. What is a header file in C? What happens if we include a header file twice?

Header files store the definitions and set of rules governing different built-in functions of the C programming language. For instance, the printf() and scanf() functions are defined in the stdio.h header file.

Every header file contains a set of predefined functions, meant to make programming in C simpler. You need to include the specific header file in your C program to be able to use the functions defined in it. You can’t use printf() and scanf() functions without including the stdio.h header file.

When a header file is included twice in a C program, the second one gets ignored. In actual fact, the #, called the include guard, preceding a header file ensures that it is included only once during the compilation process.

3. Give us a general explanation of C.

C is one of the most commonly used computer programming languages. It is a procedural language that features systematic programming, lexical variable scope, and recurrence. 

4. Why is C known as “the mother of programming languages”?

C is commonly called “the mother of programming languages” as it is the basis for many other languages. It is a time-honored language and has been widely used to develop some of the most significant compilers and kernels.

5. What are the advantages of C?

Some of the advantages of C are:

  • Middle-Level Language: As C is in the middle of a high-level language and low-level language, it has features of both. 
  • Structured Level Language: C is a structured programming language that allows a complex program to be divided into simpler programs called functions. 
  • Case Sensitive Language: It is a case-sensitive language so lower and upper case letters are treated differently.
  • Portable Language: C is a highly flexible language that enables it to be used for scripting system applications, which makes it a part of many well-known operating systems.
  • Powerful and Efficient Language: It is a user-friendly language and can effectively operate on games, graphics, enterprise applications, and applications that need some calculations, among other things.

6. What are some of the limitations of C?

The following are some of the drawbacks of C:

  • Lack of OOPs: C does not make use of OOPs as it is based on the procedural approach.
  • No Runtime Checking: C does not perform runtime checking which means that errors are not detected after every line of code.
  • No Namespaces: C does not allow namespaces, so there cannot be two variables with the same name in the C program.
  • Lack of Exception Handling: The language doesn’t exhibit the important feature of exception handling. The feature of exception handling doesn’t allow the user to detect errors and bugs while compiling the code.
  • Insufficient Level for Abstraction: C doesn’t have a very wide data handling capacity, which poses a threat to the security of the language.

Still Learning C? Take This Course

C Programming For Beginners - Master the C Language

7. What is the objective of the main () function in C?

The main () function in C to the inlet to the C program. It is the entry point where the process of execution of the program starts. When the execution of the C program initiates, the control of the program is directed towards the main () function. It is mandatory that every C program has a main () function. Although it is the function that indicates the programming process, it is not the first function to be executed.

8. What are variables and constants?

In C, both constants and variables are widely used while designing a program. The major difference between variables and constants is that variables can alter their assigned value at any point of the program. 

In contrast, the value of the constant remains unaltered during the entire program. The value of the constant is locked during the execution of the program. 

For example, the value of pi can be set as a constant during the entire course of the program.

9. Distinguish between a header file in angular braces and one in double quotes.

If the header file is placed within the angular braces < >, then the compiler finds out the specific header file only within the built-in include path. But if the header file is placed in double quotes, the compiler tries to locate the specific header file primarily in the current working directory, and if it cannot be located there, then it searches in the built-in included path.

10. Does a C program compile without the main() function? What about its execution?

Yes, a C program can be compiled even without adding the main() function. However, it will not execute without the main() function.

11. What are the basic data types in C?

There are 5 basic data types in C:

  1. int: Stores an integer number
  2. float: Stores a decimal number
  3. double: Stores a decimal number with the highest precision
  4. char: Stores a single character
  5. void: Stores no value

12. What are reserved keywords and how many are there?

Words that are restricted for general use while writing a program, i.e., for use as a name for a variable, function, structure, etc., are called reserved keywords. Reserved keywords, also called reserved names, have special meanings, i.e., they are already defined for something. 

The C programming language has the following 32 reserved keywords:

  1. auto
  2. break
  3. case
  4. char
  5. const
  6. continue
  7. default
  8. do
  9. double
  10. else
  11. enum
  12. extern
  13. float
  14. for
  15. goto
  16. if
  17. int
  18. long
  19. register
  20. return
  21. short
  22. signed
  23. sizeof
  24. static
  25. struct
  26. switch
  27. typedef
  28. union
  29. unsigned
  30. void
  31. volatile
  32. while

13. How are global variables different from static variables?

Global variables are variables with global scope, i.e., they are accessible throughout the program, unless shadowed. These variables are defined outside a function or code block. 

Static variables are variables allocated statically, i.e., their value can’t be changed. It is fixed for the entire run of a program. They can be defined outside as well as inside functions. Moreover, they can be accessed from anywhere inside the program.

14. Explain static memory allocation and dynamic memory allocation.

In dynamic memory allocation, memory can be increased while executing the program. This is not the case; however, with the static memory allocation where the option of increasing memory during program execution is not available.

Static memory allocation needs more memory space compared to dynamic memory allocation. Arrays use static memory allocation while linked lists use dynamic memory allocation. Static memory allocation takes place at compile-time, while dynamic memory allocation happens at runtime.

15. What are memory leaks? Why should it be addressed?

A memory leak happens when a memory created in a heap remains undeleted. This can lead to additional memory usage and, thus, affect the performance of a program. This is exactly why the issue of memory leaks must be addressed.

16. What is while(0) and while(1)?

while(0) is a looping condition that will always be false, i.e., the code inside the while loop will not be executed. while(1) is an infinite loop. It runs continuously until coming across a break statement mentioned explicitly.

Note: Any non-zero integer inside the braces of the while loop will give an infinite loop. For example, while(-22) and while(24) will both yield an infinite loop.

17. What is the role of a protected access specifier?

The privacy of a protected keyword lies somewhere between the keywords private and public. If a class is marked as protected, it can be accessed by its member functions, classes derived with public or protected access, privately derived classes, and friends of the class that declared these members.

18. What is the keyword volatile used for?

Volatile prevents the compiler from optimizing the variable or object in question. Any code can change the variable’s value outside the scope of the current code at any time. This implies that the compiler has to keep the value of a volatile variable in all the local copies of the variable.

19. Explain the purpose of the ‘delete’ operator.

Delete removes all the objects created by the new expression, i.e. frees memory in the heap space. The array objects are deleted using the [] operator:

delete[] array;
NULLorvoid Pointer can be deleted as:
delete ptr;

The same is applicable for user-defined data types as well. For example,

int *var = newint;
delete var;

20. Explain the purpose of extern storage specifier.

The extern storage specifier helps declare objects that can be used by many source files. It describes a variable that is externally defined. The definition can appear at the beginning of a block or outside a function. There is only one declaration of the extern variable. If any other instance is found, it is considered the same as the first one. Extern variables can have block scope or file scope depending on where they are defined.

21. What is the preprocessor?

A preprocessor is a program that produces an output that is used by some other program as an input. 

For example, translation is a preprocessing step after which the code is sent for compilation.

22. What are command-line arguments?

To control a program from outside, we supply the command line argument parameter to the program when the main method is invoked. The syntax is:

intmain(int argc, char *argv[]) 

where argc, argv are command-line arguments.

23. List out the differences between reference and Pointer?

Reference

Pointer

It is an alternative name for a variable.

Stores the address of a variable.

Declared using * : int *ptr.

Declared using & : int &refvar.

Cannot have null values.

Can have null values assigned.

Can be accessed through pass by value.

Uses pass by reference.

Must be initialized upon declaration, i.e. int &ref; will give an error.

No need for initialization during declaration itself, i.e. int *ptr is correct.

Shares same memory address as the original variable and takes up some space on the stack.

Has its size and memory address on the stack.

24. Write a program to print Hello World! Without using the semicolon.

We can do so by using the if statement without the condition:

#include <stdio.h>
#include <conio.h>
void main()
{
if
(
printf("Hello World!")
)
}

Output: Hello World!

25. What are the differences between new() and malloc()?

new()

malloc()

It is an operator.

It is a function.

Returns a data type.

Returns a void pointer.

Memory is allocated with default values through the constructor.

Memory is not initialized; the default value is garbage.

New can be overloaded.

Cannot be overloaded.

The allocations cannot be resized.

Allocations can be resized using realloc.

26. Explain the difference between delete and delete[]?

Delete removes a single object from memory, whereas delete[] is used for de-allocating memory of an array of objects. The importance of having delete[] is that if we have a pointer (say ptr) to an array of size 10 (new myarr[10]) and simply give delete ptr, since we don’t know how many objects ptr is pointing to, and thus delete will only delete the first item. The remaining 9 items will not be deleted. This will cause a memory leak. Example:

// delete
int *var = new int;
delete var;
// delete[]
int *arr = new int[1];
delete[] arr;

27. What is the difference between prefix increment and postfix increment?

In prefix increment, the value of the variable is incremented before the program execution. The variable is incremented post the program execution in postfix increment.

++a <- Prefix increment

a++ <- Postfix increment

C Intermediate Level Interview Questions

28. What is a Dangling Pointer?

A pointer that points to a memory location that is already deleted is called a dangling pointer. As per another definition, a dangling pointer is a pointer that points to a dereferenced memory location. A pointer acts as a dangling pointer in three cases:

  1. Deallocation of memory
  2. When the local variable isn’t static
  3. When the variable goes out of scope

29. How is the null pointer different from a void pointer?

A pointer is initialized as NULL when its value isn’t known at the time of declaration. Generally, NULL pointers do not point to a valid location. Unlike NULL pointers, void pointers are general-purpose pointers that do not have any data type associated with them. Void pointers can contain the address of any type of variable. So, the data type that a void pointer points to can be anything.

#include <stdio.h>
#include <conio.h>
void main()
{
int a = 22;
int *notnullpointer = &a;
int *nullpointer1; // Null because there is no initialization.
int *nullpointer2 = 0; // Null because initialized with 0.
if (notnullpointer == 0) printf ("\nNot null pointer is null.");
else printf ("\nNot null pointer is not null.");
if (nullpointer1 == 0) printf ("\nNull pointer 1 is null.");
else printf ("\nNull pointer 1 is not null.");
if (nullpointer2 == 0) printf ("\nNull pointer 2 is null.");
else printf ("\nNull pointer 2 is not null.");
printf ("\nNot null pointer has stored the address %d.", &notnullpointer);
printf ("\nNull pointer 1 has no valid address.");
printf ("\nNull pointer 2 has no valid address.");
}

Output:

Not null pointer is not null.

Null pointer 1 is null.

Null pointer 2 is null.

Not null pointer has stored the address 2054804456.

Null pointer 1 has no valid address.

Null pointer 2 has no valid address.

Unlike NULL pointers, void pointers are general-purpose pointers that do not have any data type associated with them. Void pointers can contain the address of any type of variable. So, the data type that a void pointer points to can be anything. For example:

int x = 22;
char b = 'a';
void *vp = &x; // Here the void pointer is holding address of int x
vp = &b; // Here the void pointer is holding address of char b

30. What are the calloc() and malloc() functions?

calloc() and malloc() are library functions used for allocating memory dynamically, i.e., the memory is allocated during runtime from the heap segment. In case of successful memory allocation, a pointer to the memory block is returned. In scenarios where allocation fails, the two functions return a NULL value. 

31. How is pass by value different from a pass by reference?

Pass by value and pass by reference are also called call by value and call by reference. In call by value, values are sent/passed to the function as parameters. It is used when there is a requirement of not modifying the actual parameters. Changes made to the arguments in the called function are not reflected in the calling function in a pass by value.

Pass by reference is used when there is a need for modifying the actual parameters. Addresses pertaining to the actual parameters are sent/passed to the function in the call by reference. Changes made to the arguments in the called function are reflected in the calling function in a pass by reference.

32. When is the register keyword used?

The register storage specifier, i.e., the register keyword, is used for storing a variable in the machine register. This is typically used for heavily-used variables to the likes of a loop control variable. The intent behind using the register keyword is to speed-up the program by minimizing variable access time.

33. What do you understand by rvalue and ivalue?

The expression on the left of the assignment operator (=) is called an ivalue. An rvalue is an expression on the right side of the assignment operator, and it is assigned to an ivalue.

For instance,

int a = 25;

int a is the ivalue in the above-mentioned example while 25 is the rvalue. While an ivalue persists beyond a single expression, the rvalue doesn’t persist beyond the expression using it.

34. How are actual parameters different from formal parameters?

Actual parameters are the ones that are sent to the function at the calling end. Formal parameters, however, are the ones that are received during the function definition. A formal parameter is an identifier used in some function to stand for the value that is passed into the function by a caller. This actual value that is passed into the function by a caller is the actual parameter.

Formal parameters are bound to an actual value as long as their function is active. The formal parameters do not store any values when the function returns to its caller. For example:

#include <stdio.h>
#include <conio.h>
int totalsum(int a, int b, int c) // Formal parameters
{
int total;
total = a + b +c;
return total;
}
int main()
{
int sum;
int a = 22; int m = 24; int p = 28; // Actual parameters
sum = totalsum(a, m, p);
printf ("The total sum is %d.", sum);
}

Output:

The total sum is 74.

Another major distinction between actual parameters and formal parameters is that while the latter are always variables, the former can be expressions, function calls, or even numbers. For example, in the above example, the following are also valid actual parameters (in the function call to totalsum):

sum = totalsum (10+15, 12*2, 56/2); // Actual parameters are expressions.
sum = totalsum (a, (int) sqrt(576), p); // One of the actual parameters is a function call.
sum = totalsum (22, 24, 28); // Actual parameters are numbers.

35. What is a self-referential structure?

A self-referential structure contains the same structure pointer variable as its element. 

In other words, it is a data structure in which the pointer points to the structure of the same data type. 

A self-referential structure is used in graphs, heaps, linked lists, trees, etc.

36. What is modular programming?

A modular approach to programming involves dividing an entire program into independent, interchangeable sub-programs, i.e., functions and modules for accomplishing the desired functionality. Each of the functions or modules involved in modular programming has everything required for executing a single aspect of the desired functionality of the entire program.

37. What are tokens?

Tokens are the smallest, indivisible units of a C program with distinct meanings. The following are the various types of tokens:

  • Constants: Fixed values that can’t be changed during the program execution.
  • Identifiers: Refers to the name of the functions, variables, arrays, structures, etc.
  • Keywords/Reserved Names: Predefined words with special meanings that can’t be used as variable names.
  • Operators: Symbols that tell the C compiler to perform specific logical, mathematical, or relational operations.
  • Special Characters: All characters excluding the alphabets and digits are special characters.

38. What are bit fields?

Bit fields are variables defined with a predefined width (size) inside a structure. The general syntax of a bit field is:

struct {
type [member_name] : width ;
};

type: Integer type, such as int and signed int, determining how a bit field’s value is interpreted.

member-name: Name of the bit field.

width: Number of bits in the bit field. Must be less than or equal to the bit width of the specified integer type.

39. What are the various file opening modes?

Files are opened in a C program using the fopen() function. It is defined in the stdio.h header file. The general syntax of fopen() is:

ptr = fopen (“file address”, “mode”);

It is possible to open a file in the following 12 different opening modes in a C program:

  1. r - Opens a file for reading.
  2. rb - Opens a file for reading in binary mode.
  3. w - Opens a file for writing.
  4. wb - Opens a file for writing in binary mode.
  5. a - Opens a file for appending i.e. adding data to the end of the file.
  6. ab - Opens a file for appending in binary mode.
  7. r+ - Opens a file for both reading and writing.
  8. rb+ - Opens a file for both reading and writing in binary mode.
  9. w+ - Opens a file for both reading and writing.
  10. wb+ - Opens a file for both reading and writing in binary mode.
  11. a+ - Opens a file for both reading and appending.
  12. ab+ - Opens a file for both reading and appending in binary mode.

Except for r, rb, r+, and rb+ modes; the file is created if it is not found when tried to open in other modes. The fopen() returns NULL if the file doesn’t exist in these 4 file opening modes.

40. What is recursion?

Recursion is the process when a function calls itself, directly or indirectly. Such a function is called a recursive function. There are two phases involved with a recursive function:

  1. Winding phase: It starts when the recursive function calls itself and ends once the condition is reached.
  2. Unwinding phase: Starts when the condition is reached, i.e., when the winding phase ends, and ends when the control returns to the original call.

41. Write a C program to check whether the entered number is a prime number.

#include <stdio.h>
#include <conio.h>
void main()
{
int a, i, b=0, flag=0;
printf("Enter a number: ");
scanf("%d",&a);
b=a/2;
for(i=2;i<=b;i++)
{
if(a%i==0)
{
printf("The number you entered is not a prime number!");
flag=1;
break;
}
}
if(flag==0)
printf("The number you entered is a prime number.");
getch();
}

Sample output:

Enter a number: 22

The number you entered is not a prime number!

42. Write a program for finding out the factorial of a given number using recursion.

#include <stdio.h>
#include <conio.h>
long factorial (int n)
{
if (n==0)
return 1;
else
return (n * factorial(n-1)); //recursion
}
void main()
{
int number;
long fact;
printf("Enter a number: ");
scanf("%d", &number);
fact = factorial(number);
printf("The factorial of %d is %ld!\n", number, fact);
getch();
}

Sample output:

Enter a number: 5

The factorial of 5 is 120!

C Advanced Level Interview Questions

43. What is a far pointer?

A far pointer is a 32-bit pointer capable of accessing all the 16 segments, i.e., the whole residence memory of RAM. It can access information outside the computer memory in a given segment. To use the far pointer, it is required to:

  • Allocate the sector register to store data address in the segment, and
  • Store another sector register within the most recent sector

44. What is the auto keyword?

auto is the default storage class of all the variables declared inside a code block or function. Local variables can also be referred to as automatic or auto variables. If no value is stored in an auto variable, then it gets a garbage value. Auto variables are called so because these variables allocate and deallocate memory upon entering and exiting the code block or function in which they are declared, respectively. Typically, there is no need to mention the auto keyword explicitly.

45. Why do we use the sprintf() function?

The sprintf() function is called string print. We use the sprintf() function to store the output on a character buffer specified in the function, i.e., transferring data to the buffer. The general syntax of the function is:

intsprintf
(char *str, constchar*string,.....);

The sprintf() function returns the total number of characters present in the string. Here is an example demonstrating the use of the sprintf() function: 

#include <stdio.h>
#include <conio.h>
int main()
{
char buffer[25];
sprintf(buffer, "This string is now stored in the buffer."); /* Using the sprintf() function for storing the string in the buffer.*/
printf("%s", buffer);
int n = sprintf(buffer, "This string is now stored in the buffer.");
printf("\nThe total number of characters in the string is %d.", n); // The sprintf() function returns the total number of characters in the stored string.
return 0;
}

Output: This string is now stored in the buffer.

The total number of characters in the string is 40.

46. What is the difference between getch() and getche() functions?

Both getch() and getche() functions are used for reading a single character from the keyboard. The difference between the two, however, lies in terms of displaying the output. The getche() function displays the data, the entered character, on the output screen while the getch() function doesn’t. Use Alt+F5 to see the entered character.

47. What is the difference between near, far, and huge pointers?

Any virtual address has the selector and offset. While a near pointer doesn’t have an explicit selector, far and huge pointers do. Performing pointer arithmetic on the far pointer doesn’t result in modifying the selector. It does, however, in the case of a huge pointer.

48. What is typecasting?

Typecasting is the process of converting one data type into another. There are two types:

  1. Implicit type casting: Also known as an automatic conversion, implicit type conversion is performed automatically by the C compiler, i.e., it doesn’t require a casting operator. For example:
#include <stdio.h>
#include <conio.h>
void main ()
{
int x = 22;
float b = x; //implicit type conversion
printf(“%f”, b);
}

Output: 22.000000

  1. Explicit type casting: Unlike implicit type conversion, explicit type casting is performed by the programmer. A type casting operator is used for telling the compiler to convert (cast) one data type into another. For example:
#include <stdio.h>
#include <conio.h>
void main ()
{
float x = 22.22;
int b = (int) x; //explicit type conversion
printf(“%d”, b);
}

Output: 22

Here, (int) is the typecasting operator.

49. Write a C program to check whether an entered number is a palindrome.

A palindrome number is one that reads the same, whether forwards or backwards. 

#include<stdio.h>
#include<conio.h>
void main()
{
int n, r, sum=0, temp;
printf("Enter a number: ");
scanf("%d",&n);
temp=n;
while(n>0)
{
r=n%10;
sum=(sum*10)+r;
n=n/10;
}
if(temp==sum)
printf("It is a palindrome number!");
else
printf("It is not a palindrome number!");
getch();
}

Sample output:

Enter a number: 12321

It is a palindrome number!

50. What is the #undef preprocessor?

As per the C programming language, the main aim of the #undef directive is that it acts as a guide to the preprocessor to get rid of all the definitions for the particular macro. If a macro is non-specific, and #ifdef directive on that specified macro will show the result as false.

Conclusion

That sums up our list of the top C interview questions. If you want to polish your C programming skills before the interview, feel free to check out these best C tutorials and this C Programming For Beginners Udemy course.

Frequently Asked Questions

1. What are the basic C interview questions?

The C programming interview questions we have listed above cover the basics and more. Expect everything from questions on data types to the advantages and disadvantages of C.

2. What is C Commonly Used for?

C is used for a wide variety of purposes, from designing operating systems to games. The interview questions on the C language listed above explains this in more detail.

People are also reading:

Vijay Singh

Vijay Singh

My name is Vijay Singh Khatri, and I enjoy meeting new people and finding ways to help them have an uplifting experience. I have had a variety of customer service opportunities, through which I was able to have fewer returned products and increased repeat customers, when compared with co-workers. Currently working with hackr.io View all posts by the Author

Leave a comment

Your email will not be published
Cancel
sujith
sujith

The answer for the question How are global variables different from static variables is wrong because the static variables can be incremented. please check the answer

TODAY'S OFFERS
close

Select from the best sales here

VIEW ALL DISCOUNTS