C Interview Questions and Answers for Freshers

    1 Votes

Top 75+ frequently asked C Programming Interview Questions and Answers for Freshers and 0-2 year experienced C programmers asked in various interviews and competitive exams.

1) What is the difference between #include <file> and #include "file" ?

We use # include to include a file. The difference between two ways of file inclusion lies in the order in which preprocessor searches for the file specified. When the preprocessor encounters #include<file> statement, it looks for the file specified in the angled brackets in the default location (Path defined in INCLUDE environment variable of the system).

When # include followed by file name in double quotation marks is encountered by the preprocessor, it looks for the file in the current directory. If the file is not found in the current directory, it will look for the file in the default location.

2) Can #include handle other file formats than .h?

Yes. Irrespective of the file type, Preprocessor will do its job and will include any file like test.z.

3) What is a void pointer?

A void pointer is a special pointer type which can point to any data type without letting the compiler know. It helps to pass a pointer to some function of any type which can be decided at run time. In the following example input parameter a and b can be both integer and string.

Void PointerVoid(int type, void *a, void *b, void *c)
   if(type == 1)/* int*/
   *c = ((int) *a) + ((int)*b);
   else /*string*/

4) What is the value of NULL?

The value of NULL is 0 or (void*)0. Whenever NULL has to be compared with some variable or assigned to a variable, depending upon the type of that variable, the value of NULL will be decided.

5) Can the size of an array be declared at runtime?

No. The size of an array must be stated at the time of compilation. Alternate way is to use dynamic allocation by calloc or malloc.

6) what is the difference between malloc() and calloc()?

Allocates a region of memory large enough to hold "n” elements of "size" bytes each. Allocates "size" bytes of memory.
Calloc initializes the whole memory with 0 Malloc does not change the existing memory. So it returns a memory chunk with garbage value.

7) What is the heap in memory?

The heap is where malloc(), calloc(), and realloc() get memory. The allocation of memory from the heap is much slower than the stack. But, the heap is much more flexible about memory allocation than the stack. Memory can be allocated and deallocated in any time and order. This heap memory isn't deallocated by itself, method free() has to be called in order to do so.

8) What will be the output of the following code snippet?

float num1 = 6 / 4;
float num2 = 6 / 4.0;
printf("6/4 == %f or %f\n", num1, num2);

Output will be : 6/4 == 1.000000 or 1. 500000. This is a case of operator promotion. The variable num1 is set to “6/4”. Because, both 3 and 4 are integers. So integer division is performed on them and the result is the integer 0. The variable num2 is set to “6/4.0”. Because 4.0 is a float, the number 6 is converted to a float as well, and the result will be floating value 1.5.

9) What happens if you free a pointer twice?

It is really dangerous to free the same memory twice. If the memory has not been reallocated in between, it will generate a “double free” error, since the memory location has already been freed.

10) How does free() method know about how much memory to release?

There's no concrete way. Most systems, keeps a track of each memory block as linked lists. When memory is allocated, all the blocks that are given to that particular call are put into a linked list and the size, block number and serial number are written in the head node. There is no assurance, though. But in some way or other, the system keeps track of each block to know the size of each allocated portion of the heap.

11) How to restrict a header file from including more than once?

In C, to avoid double inclusion, we use a include guard also known as macro guard. It is #ifndef - #endif pair. "ifndef" is an indication of “if not defined”.

#ifndef FAMILY_H
#define FAMILY_H
struct Example
  int member;
#endif /* FAMILY _H */

12) How to print an address?

The best way is to use "%p" in printf() or fprintf. The “%p” will tell compiler to use the best type to use, while printing the address according to the environment, since the size of a pointer changes from system to system.

13) Enter the output of the program

#include <stdio.h>
enum day {sunday = 1,monday,tuesday,wednesday,thursday = 3,friday,saturday};

int main()
  int i;
  printf("%d %d %d %d %d %d %d", sunday, monday, tuesday,
  wednesday, thursday, friday, saturday);
  return 0;

The answer is : 1 2 3 4 3 4 5

Explanation: The enum assigns the value with single increment. If a value is explicitly assigned to an element, it will just set that value to that element and start to increment from that assigned value for the following elements.

14) Explain recursive functions? Also explain the advantages and disadvantages of Recursive algorithms?

A recursive function is a function which calls itself. The advantages of recursive functions are:

  • A substitute for very complex iteration. For example, a recursive function is best to reduce the code size for Tower of Hanoi application.
  • Unnecessary calling of functions can be avoided.

The disadvantages of Recursive functions:

  • The exit point must be explicitly coded ,otherwise stack overflow may happen
  • A recursive function is often confusing. It is difficult to trace the logic of the function. Hence, it is difficult to debug a recursive function.

15) What are the standard predefined macros?

ANSI C has six predefined macro. They are

  • __FILE__ - Name of the current file
  • __LINE__ - Current line number
  • __TIME__ - Current time of compilation
  • __DATE__ - Current date of compilation
  • __cplusplus - If program compiled in C++ compiler
  • __STDC__ - If ANSI C is followed by the compiler strictly.

16) What is a pragma?

The #pragma preprocessor allows compiler to include or exclude compiler specific features. For example if there is a feature xxx_yyy then,
#pragma xxx_yyy(on)
Forces compiler to include the feature. Conversely, you can turn off it by the following lines:
#pragma xxx_yyy(off)


17) How to redefined macro with different value?
The #undef preprocessor can be used to reset a macro. For example,
#ifdef SAMPLE /* Checking if SAMPLE is defined */
#undef SAMPLE /* If so, then reset it */
#define SAMPLE 0 /* Then redefine with intended value */


18) What is an lvalue?

An lvalue is an expression to which a value can be assigned. The lvalue expression is the one which is located on the left side a statement, whereas an rvalue is located on the right side of a statement. Each assignment must have a valid lvalue and rvalue. The lvalue expression must refer to a storage where something can be stored. It can't be a constant.

19) How to assign one array to another?

You can't assign an array to other. Arrays are not lvalue, because they don't refer to one variable, rather a set of variables. So they can't be placed on the left hand side of an assignment statement. For example the following statement will generate compilation error.

int x[5], y[5];
x = y;

20) what is the order of operator precedence, left to right or right to left ?

None of them is standard. C does not always start evaluating left to right or right to left. Normally, function calls are done first, followed by complex expressions and then simple expressions. That is why it is best to use parenthesis in all expressions, without depending on precedence.

21) What is the difference between ++X and X++?

The ++ operator is called the incremental operator. When the operator is placed before, the variable is incremented by 1 before it is used in the statement. When the operator is placed after the variable, then the expression is evaluated first and then the variable is incremented by 1.

22) What happens when we use incremental operator in a pointer?

It depends upon the type of the pointer. It gets incremented by the size of the data type, the pointer is pointing to. For example

char p; p++; /* here p increments by 1*/
int p; p++;/* here p increments by 4(for 32 bit system)*/

23) What will be output of the following code snippet?

int num1=5;
int num2=5;
num1 =num1++ + num1--;
num2 =++num2 + --num2;
printf("num1=%d num2=%d",num1,num2);

Output will be num1=10 num2=10.

24) Can the sizeof operator be used to tell the size of an array passed to a function?

No. The sizeof() operator can't tell the size of an array, because it is actually a pointer to the data type of the array.

25) Can you change the value of an array tag?

No. An array tag can't be used as a storage, because it is not an Lvalue. It can be thought as a pointer to the datatype of the array which is constant and which can't be changed or assigned dynamically.

26) What is a stream? How many types of streams are in C?

A stream is a series of data bytes which serves the input and output needs of a program. Input and output from devices are generally connected to these streams which then appears as logical file descriptors to your program. In C, there are five such standard streams which need not be opened or closed explicitly.
stdin Standard Input Keyboard
stdout Standard Output Screen
stderr Standard Error Screen
stdaux Standard Auxiliary COM1: port
stdprn Standard Printer LPT1: port


27) What are text and binary modes?

Streams can be classified into two types: text streams and binary streams. The text streams are interpreted as per the ASCII values starting from 0 to 255. Binary streams are raw bytes which C can't interpret, but application has to interpret it itself. Text modes are used to handle, generally text file where as binary modes can be used for all files. But they won't give you the content of a file, rather they will give you the file properties and content in raw binary format.

28) Which one to use, a stream function or a system calls?

Stream files are generally better to use, since they provide sufficient amount of buffer for read and write. That is why it is more efficient.

But in a multiuser environment, files can be shared among users. These shared files are secured with lock, where only one user will be able to write at a time. In this scenario, buffering will not be efficient, since the file content will change continuously and it will be slower.

So, normally it is good to use stream functions, but for shared files system calls are better.

29) What is the difference between a string copy (strcpy) and a memory copy (memcpy)?

Generally speaking, they both copy a number of bytes from a source pointer to a destination pointer. But the basic difference is that the strcpy() is specifically designed to copy strings, hence it stops copying after getting the first '\0'(NULL) character. But memcpy() is designed to work with all data types. So you need to specify the length of the data to be copied, starting from the source pointer.

30) How can I pad a string to a known length?

printf("%-20.20s", data[d]);

The "%-20.20s" argument tells the printf() function that you are printing a string and you want to force it to be 20 characters long. By default, the string is right justified, but by including the minus sign (-) before the first 20, you tell the printf() function to left-justify your string. This action forces the printf() function to pad the string with spaces to make it 20 characters long.

31) How can I convert a number to a string?

The following functions can be used to convert integers to strings:

Function NamePurpose
itoa() Integer value to a string.
ltoa() Long integer value to a string.
Ultoa() Unsigned long integer value to a string.

You can write your own functions too, because these functions are not that safe, as they don't check if the value given is NULL or not.

32) What does const keyword do?

The access modifier keyword “const” tells compiler that the value of this variable is not going to be changed after it is initialized. The compiler will enforce it throughout the lifetime of the variable.

33) char *p="SAMPLETEXT" , *q ="SAMPLETEXT"; Are these two pointers equal ? If yes , then explain ?

In C, strings(not array of characters) are immutable. This means that a string once created cannot be modified. Only flushing the buffer can remove it. Next point is, when a string is created it is stored in buffer. Next time, when a new string is created, it will check whether that string is present in buffer or not. If present, that address is assigned. Otherwise, new address stores the new string and this new address is assigned.

34) When should a type cast be used?

There are two main uses of type cast.

  • The first one is to convert some value of datatype A to a datatype B. Such as, if you type cast a float variable of value 1.25 to int, then it will be 1.
  • The second use is to cast any pointer type to and from void *, in order to use it in generic functions such as memory copy functions, where the execution is independent of the type of the pointer.

35) What is the difference between declaring a variable and defining a variable?

Declaration is done to tell compiler the data type of the variable, and it inherently meant that somewhere in this scope, this variable is defined or will be defined. And defining a variable means to allocate space for that variable and register it in the stack memory. For example:

extern int decl1; /* this is a declaration */
int def2; /* this is a definition */

36) Can static variables be declared in a header file?

You can't declare a static variable without definition (this is because they are mutually exclusive storage classes). A static variable can be defined in a header file, but then every source file with in that scope will have their own copy of this variable, which is intended.

37) What is the benefit of using const for declaring constants over #define?

The basic difference between them is that, a const variable is a real variable which has a datatype and it exists at run time, and it can't be altered. But a macro is not a real variable, but it carries a constant value which replaces all the occurrences of that macro at the time of pre-processing.

38) What is a static function?

Static function is a special type of function whose scope is limited to the source file where the function is defined and can not be used other than that file. This feature helps you to hide some functions and to provide some standard interface or wrapper over that local function.

39) Should a function contain a return statement if it does not return a value?

In C, void functions does not return anything. So it is useless to put a return statement at the end of the function, where the control will any way return to the caller function. But, if you want to omit some portion of the function depending upon the scenario, then this return statement is perfect to avoid further execution of that void function.

40) How can you pass an array to a function by value?

An array can be passed to a function by value, by keeping a parameter with an array tag with empty square brackets(like []). From the caller function, just pass the array tag. For instance,

void func(int i[]) {..} /* parameter */
int k[10];
func(k); /* caller function */

41) Is it possible to execute code even after the program exits the main() function?

There is a standard C function named atexit() for this purpose that can be used to perform some operations when your program exiting. You can register some functions with atexit() to be executed at the time of termination. Here's an example:

#include <stdio.h>
#include <stdlib.h>
void _some_FUNC_(void);
int main(int argc, char** argv)

42) What does a function declared as PASCAL do differently?

In C, when some function is called, the parameters are put at the top of the stack. Now the order in which they are put is the order in which the parameters are parsed. Normally, the order is right to left. That is, the right most is parsed first and the left most parameter is parsed at last.

If you want to alter this paradigm, then you have to define the function with PASCAL as following:

int PASCAL pascal_func(int, char*, long);

Here, the left most parameter(int) will be parsed first, then char* and then long.

43) Why does PASCAL matter? Is there any benefit to using PASCAL functions?

The main reason behind using PASCAL is that, in the left-to-right parsing the efficiency of switching increases in C.

44) Is using exit() the same as using return?

No. They are not the same. Return statement returns control to the caller function, that is, it exits from the lowest level of the call stack. Where as, exit statement make the program returns to the system from where the application was started. So, exit always exits from the highest level of call stack. Eventually, if there is only one level of function call then they both do the same.

45) Point out the error in the program given below, if any ?

  int a=10,b;
  a>= 5 ? b=100 : b=200;

A value is required in function main(). The second assignment should be written in parenthesis as follows:

a>= 5 ? b=100 : (b=200);

46) Point out the error in the following program

  const int x;
  x = 128;

Variable x should have been initialized during declaration.

47) In C, what is the difference between a static variable and global variable?

A static variable ia declared outside of any function and it is accessible only to all the functions defined in the same file (as the static variable). In case of global variable, it can be accessed by any function (including the ones from different files).

48) Write a c program to print Hello world without using any semicolon.
void main()
   if(printf("Hello world"))

Same way, while and switch statements can be used to achieve this.

49) Write a C program to swap two variables without using third variable ?

int main()
  int a=5,b=10;
  printf("a= %d b= %d",a,b);

50) What is dangling pointer in c?

If any pointer is pointing at the memory location/address of any variable, but if the variable is deleted or does not exist in the current scope of code, while pointer is still pointing to that memory location, then the pointer is called dangling pointer. For example,

int *func();
int main()
  int *ptr;
  return 0;
int * func()
  int x=18;
  return &x;

Output is Garbage value, since the variable x has been freed as soon as the function func() returned

51) What is wild pointer in c?

A pointer is known as wild pointer c, if it has not been initialized. For Example:

int main()
  int *ptr;
  return 0;

Output: Any address, Garbage value.

Here ptr is wild pointer, because it has not been initialized. Wild pointer is not the same as NULL pointer. Because, NULL pointer doesn't point to any location, but a wild pointer points to a specific memory location but the memory may not be available for current application, which is very fatal.

52) What is the meaning of prototype of a function?

Declaration of function is known as prototype of a function. Prototype says the name, parameter list and return type of a function but not the definition, this is same as declaring some variable but not defining it. For example,

int printf(const char *, int/);

53) Write a c program to find size of structure without using sizeof operator?

struct XXX
  int x;
  float y;
  char z;
int main()
  struct XXX *ptr=(struct XXX *)0;
  printf("Size of structure is: %d",*ptr);
  return 0;

54) What is size of void pointer?

Size of all pointers are same in C, regardless of their type because pointers variable holds a memory location. And for a given system, this size is constant. The type of pointer is used to know the size of the data that the pointer is pointer is pointing to.

55) What will be output of following program?
int main()
  int a = 260;
  char *ptr;
  ptr =( char *)&a;
  printf("%d ",*ptr);
  return 0;
(A) 2  (B) 260  (C) 4 (D) Compilation error  (E) None of above

Answer is B. 260 will take two byte memory space to reside and the bytes will be 1 and 4. Binary value of 260 is 00000001 00000100 (In 16 bit). So, ptr is only pointing to first 8 bit whose decimal value is 4.

56) What will be the output?

#include "stdio.h"
int main()
  char arr[100];
  printf("%d", scanf("%s", arr));
  /* Say the input is “hello” */
  return 1;

The scanf returns the number of inputs it has successfully read, so the output will be 1.

57) Guess the output.

#include <stdio.h>
int main()
  printf(6 + “Hello World”);
  return 0;

The printf is a library function which takes a char pointer as input. Here the pointer in incremented by 6, so the pointer will advance from pointing 'H' to 'W'. So the output will be “World”.

59) Guess the output?

#include <stdio.h>
int main()
  printf("%c ", 6[“Hello World”]);
  return 0;

In C, X[5] and 5[X] are the same. Here, 6[“Hello World”] will return the 6th element of the array “Hello World”, that is 'W'.

60) Guess the output?

#include <stdio.h>
  char *p = 0;
  *p = 'a';
  printf("value in pointer p is %c\n", *p);

a) It will print a b) It will print 0 c) Compile time error d) Run time error

Answer is d, runtime error. Because the pointer p is declared, but not the variable it is pointing to. In the statement, while assigning 'a', it will try to write in the address 0 and will get runtime error.

61) Which of the following is true

(A) gets() can read a string with newline chacters but a normal scanf() with %s can not.
(B) gets() can read a string with spaces but a normal scanf() with %s can not.
(C) gets() can always replace scanf() without any additional code.
(D) None of the above

Ans: (B)

62) What is the output of this C Program?

int main()
  printf("%d", printf("%d", 1234));
  return 0;

Answer is 12344. 1234 will be printed by the second printf and it will return 4 as printf returns the number of letters it printed.

63) How do you use a pointer to a function?

The hardest part about using a pointer-to-function is declaring it. Consider an example. You want to create a pointer, pf, that points to the strcmp() function. The strcmp() function is declared as shown below

int strcmp( const char *, const char * )

To set up “pf” to point to the strcmp() function, you want a declaration that looks just like the strcmp() function's declaration, but that has *pf rather than strcmp:

int (*pf)( const char *, const char * );

Notice that you need to put parentheses around *pf.

64) When would you use a pointer to a function?

Pointers to functions are interesting, when you pass them to other functions. A function that takes function pointers says, in effect, "Part of what I do can be customized. Give me a pointer to a function, and I'll call it when that part of the job needs to be done. That function can do its part for me. This is known as a callback". It's used a lot in graphical user interface libraries, in which the style of a display is built into the library but the contents of the display are part of the application.

65) How to return two variables of different data type from a function?
  int integerVar;
  char characterVar;
STRUCTURE Function()
  return (x);


66) What is the difference between far pointer and near pointer ?

Compilers for PC compatibles, use two types of pointers.

  • Near pointers are 16 bits long and can address a 64KB range. Far pointers are 32 bits long and can address a 1MB range. Near pointers operate within a 64KB segment. There's one segment for function addresses and one segment for data.
  • Far pointers have a 16-bit base (the segment address) and a 16-bit offset. The base is multiplied by 16, so a far pointer is effectively 20 bits long. For example, if a far pointer had a segment of 0x7000 and an offset of 0x1224, the pointer would refer to address 0x71224. A far pointer with a segment of 0x7122 and an offset of 0x0004 would refer to the same address.

67) When should a far pointer be used?

Sometimes, you can get away with using a small memory model in most of a given program. Somethings may not fit in your small data and code segments.

When that happens, you can use explicit far pointers and function declarations to get at the rest of memory. A far function can be outside the 64KB segment, most functions are shoehorned into for a small-code model. (Often, libraries are declared explicitly far, so they'll work no matter what code model the program uses.)

A far pointer can refer to information outside the 64KB data segment. Typically, such pointers are used with farmalloc() and such, to separately manage a heap from the rest of the data.

68) Expand the following fragment of C code to make it more understandable ?

{char* x = *y ? *++*y : *++*z;} 

Code can be rewritten as

char *x;
if (*y != NULL)
  x = *y;
  x = *z;

69) Write a C program to print a semicolon without using any semicolon in the whole program?

#define SEMICOLON 59 
//59 is ASCII value of semicolon 
void main() 

70) How can you determine the size of an allocated portion of memory?

You can't. free() can, but there's no way for a program to know the use of method free()

71) Add your code in the program so that the given code block print 'unknown' ?

<...Add your code...>
if(a>10) printf("greater"); 
else if(a<10) printf("lesser"); 
else if(a==10) printf("equal"); 
else printf("unknown");

#define a b++ 
  int b = 10;
  if(a>10) printf("greater"); 
  else if(a<10) printf("lesser"); 
  else if(a==10) printf("equal"); 
  else printf("unknown");

Explanation: After macro expansion the code will be like this :

if(b++>5) printf("greater"); //5>5 : fail 
else if(b++<5) printf("lesser"); //6

72) Can math operations be performed on a void pointer?

No. Pointer addition and subtraction are based on advancing the pointer by a number of elements. By definition, if you have a void pointer, you don't know what it's pointing to, so you don't know the size of what it's pointing to. If you want pointer arithmetic to work on raw addresses, use character pointers.

73) How many parameters should a function have?

There is no fixed guideline or limit to the number of parameters your functions can have. However, it is considered bad programming style for your functions to contain an abnormally high (eight or more) number of parameters. The number of parameters a function has also directly affects the speed at which it is called - the more parameters, the slower the function call.

74) Is using exit() the same as using return?

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.

75) Is it valid to address one element beyond the end of an array?

It's valid to address it, but not to see what's there. (The really short answer is, "Yes, so don't worry about it.") With most compilers, if you say

int i, a[MAX], j;

Then either i or j is at the part of memory just after the last element of the array. The way to see whether i or j follows the array is to compare their addresses with that of the element following the array. The way to say this in C is that either

& i == & a[ MAX ]

is true or

& a[ MAX ] == & j

is true. This isn't guaranteed.

Popular Videos


How to improve your Interview, Salary Negotiation, Communication & Presentation Skills.

Got a tip or Question?
Let us know

Related Articles

C++ Interview Questions and Answers for Freshers, Experienced
Advanced C Interview Questions and Answers for Experienced
Embedded C Interview Questions and Answers