Learn C Online - C Interview Questions

X




Resources > C Interview Questions > {{currentSubTopic}}

Introduction


Differentiate Source Codes from Object Codes.

Source code is the code that the programmer writes in the textual, human-readable form. For the code to be executed, it needs to be converted into binary code that is understood by the computer. This binary code is called the Object code.


What is the difference between void main() and void main (void) ?

In C, if a function signature doesn’t specify any argument, it means that the function can be called with any number of parameters or without any parameters. However, when function signature contains an argument, it means that the function can be called only with the specified argument. So technically, the signature void main (void) is better as it clearly specifies that main can only be called without any parameter.


In C programming, how do you insert quote characters (‘ and “) into the output screen?

In order to insert ‘ and ‘’ on the output screen, we use the / escape character. The escape character does not print the / and prints the character next to it as is. Hence if we want to print the following in the output screen,
“Hello”
The statement for that will be:
printf(“\”Hello\””);
Similarly if we want to print the output as This world’s great karma and the printf statement would be:
printf(“This world\’s great karma”);


Difference between compilers from interpreters.

Programs are usually written in high level language which needs to be converted to binary or machine code, in order for the computer to understand and execute it. Compilers and Interpreters are programs that are responsible for performing this conversion.
Though the task performed by both is similar there are some major differences as regards to how the conversion is accomplished.
Following table highlights some key differences:



What are reserved words?

Reserved words are special words designed to do a specific task the meaning of which is already known to the compiler. Since it is pre-defined, it cannot be used as identifiers. There are only 32 keywords available in C. These words are also known as keywords.


Is it possible to create your own header files?

Yes. It is possible to create our own header files in C as follows:
1) Open a file and write a normal C function definition. For example:

int add( int a,int b){
	return(a+b);
}

2) Save the file with a .h extension. Suppose we saved it as customHeader.h
3) The header file is now created. It can be used in any program by including it just as we include normal built in C header files:

#include<stdio.h>
#include"myhead.h"
 
void main() {
	int num1 = 10, num2 = 10, num3;
	num3 = add(num1, num2);
	printf("Addition of Two numbers : %d", num3);
}

Are comments included during the compilation stage and placed in the EXE file as well?

No comments are ignored by the compiler.


What are header files and what are its uses in C programming?

Header files are files with .h extension that contain C function definitions. These functions can be directly called and used in C programs by just including the header file using #include directive. Header files are useful when we have certain utility functions that may be required across multiple programs. Rather than having to define the functions multiple times, they can be defined once in the header file and used in any programs by just including the header file.


What is the return values of printf and scanf?

Both the functions return an int. It returns the number of characters printed, or a negative value if there was an output error. For scanf, it is normally the number of successful assignments.
Example:
int x = printf(“Programming”); // x will hold the value 10 i.e. the length of the word Programming
When we do:
int var1, var2;
int val = scanf(“%d%d”,&var1,&var2); // val will store the value 2 if we enter 2 integers.


What is the difference between #include "..." and #include <...>?

The difference is in the location where the preprocessor searches for the included file. For #include "filename" the preprocessor searches in the same directory as the file containing the directive. This method is normally used to include programmer-defined header files. For #include <filename> the preprocessor searches the search directories pre-designated by the compiler/IDE. This method is normally used to include standard library header files.


What is use of %n in printf()?

In C printf(), %n is a special format specifier which instead of printing something causes printf() to set the variable specified as the second argument to the number of characters that have been printed by printf() before the occurrence of %n.
For example:

#include<stdio.h>
 
int main()
{
  int c;
  printf("cheer for %nme ", &c);
  printf("%d", c);
  getchar();
  return 0;
}

In the above program the first printf sets the variable c to 10 as 10 characters are printed by it before the occurrence of %n.


Does Linux Ubuntu supports the Header file conio.h?

conio.h is a C header file used in old MS-DOS compilers to create text user interfaces. GCC compiler in Ubuntu, and Linux systems has different header files to include the working of what conio.h has to offer.


What will be the output of printf(“%d”)?

The statement above gives a warning with the GCC compiler. It does not give an error and prints a random value when executed.


Data Types, Operators and Control Statements


Can I use “int” data type to store the value 32768? Why?

Using int as is, we cannot store the value 32768 in a DOS based system where an int is allocated 2 bytes of memory. However, in a Linux based system with a GCC compiler we can since an int occupies 4 Bytes of memory.

Assuming we are in a DOS based system, whenever we declare an int variable, it is by default short signed i.e. one of the bits is used for indicating sign leaving us only 15 bits. The maximum value we can store in these 15 bits is 32767. However, in the short unsigned int, and the long int versions we can store the value 32768.


Which of the following operators is incorrect? ( >=, <=, <>, ==)

The operators <=, >= and == are relational operators and help in finding the relation between the operands. However <> is not an operator.


What is the difference between Do While Loop and While Loop?

In do..while, the condition is not tested until the body of the loop has been executed once. It is called as post-test loop. In the while loop, by contrast, the test is made on the entry to the loop rather than at the end. Therefore in do..while loop, the body of the loop will be executed at least once, even if the condition is false. Whereas in while loop, if the condition is false, the body will not be executed.


Is using exit() the same as using return?

return causes the control to return from the currently executing function to the point where the current function was called. exit() is a system call which terminates the program. The only case when both do (nearly) the same thing is in the main() function, as a return from main performs an exit().


Predict the output of the following code:

#include <stdio.h>

int main() {
int x=1,y=4,z=2;

int r= x<<z^y;
printf("%d",r);
	return 0;
}

Answer: 0


State the precedence order of C operators.

Following table lists the C operators in the order of their precedence:



What is the difference between the = symbol and == symbol?

= is an assignment operator that assigns the value specified on its right hand side to the variable specified on its left hand side. For example, x = 3 will assign the value 3 to x. == is a comparison operator which checks for equality of its two operands. It returns true if they are equal and false otherwise. For example, x == 3 will check if the value of x is 3.If yes, it will return true else it will return false.


Pointers, Arrays, Multidimensional Arrays and Strings


What is NULL pointer in C?

For each pointer type C defines a special pointer value which is guaranteed not to point to any object or function of that type. This pointer is called the NULL pointer.


What is pointer to pointer in C?

int p=10,*ptr;
ptr is a pointer variable that contains the base address of a variable of type int.
int **aptr;
aptr is a pointer variable that contains the address of a single pointer variable of type integer.
int ***bptr;
bptr is a pointer variable that contains the address of a double pointer variable, which contains the base address of another variable of type integer.

int  p,*ptr,**aptr,***bptr;

p=10;
ptr=&p;
aptr=&ptr;
bptr=&aptr;
printf(“%u - %u - %u”, ptr,aptr,bptr);
			6552- 6554 – 6556
printf(“%u -%u -%u”,*ptr,*aptr,*bptr);
			10 – 6552 – 6554
printf(“%d-%d-%d”,*ptr,**aptr,***bptr)
			10 – 10 - 10


What is a Void Pointer?

A void pointer in C is a pointer that can point to a variable of any data type.
Example:

void *vp;
int a = 300, *ip;
float f = 12.2, *fp;
char ch = 'a';
vp = &a; // ok
vp = ip; // ok
vp = fp; // ok

A void pointer cannot be dereferenced to any other pointer.


How can a string be converted to an int?

A string can be converted to int using either the atoi() or the strtol() functions. More functions are available, these ones are the most commonly used where strtol is slightly better.


What is the difference between ‘B’ and “B”?

‘B’ is a character constant whose corresponding ASCII value is stored in the memory. However “B” is a string constant. A string constant is nothing but an address referring to the first character in the string.


What is the use of a ‘\0’ character?

It is referred to as a terminating null character, and is used primarily to show the end of a string value.


Are ++*ptr and *ptr++ are same ?

No.


What are wild pointers in C?

Uninitialized pointers are called Wild pointers. They point to arbitrary memory locations and cause lot of bad behaviour in program.


What is a dangling pointer?

A pointer is said to be a dangling pointer when the variable pointed to by the pointer has been deleted.


What is the output of the following code?

#include <stdio.h>

int main() {
    int a[2][3][2]={{
                        {2,4},
                        {7,8},
                        {3,4}
                    },
                    {
                        {2,2},
                        {2,3},
                        {3,4}
                    }
    };
    printf("%u ",***a+1);
	return 0;
}

Answer : 3


Functions and Structures


What is the difference between Call by Value and Call by Reference?





What are advantages and disadvantages of recursive calling ?

Advantages of Recursion:
Recursion means breaking down the problem into a smaller problem of the same type. Often the code written is very concise and easy to understand .

Disadvantage of Recursion:
Every call has a call stack that is maintained. Thereby the execution time is very slow as compared to an iterative solution.


How to implement variable argument functions ?

The following is an example of variable argument function as written in the GCC compiler.

#include<stdio.h>

int func(int v, ... ) {
   
}

int main() {
   func(1, 2, 3);
   func(1, 2, 3, 4);
}

What are Storage Classes in C ?

Every variable in a program has some memory associated with it. Memory for a variable is allocated and released at certain point of a program. The period of time during which memory is associated with a variable is called the extent of the variable.

int fun()
{ int x;
x=10;
printf(“%d”,x);
return x;
}

In the above example, memory is allocated for x when the function is called. Similarly the memory is released when the function returns. The lifetime of a variable is characterized by it’s storage class. The storage class can be classified into the following groups:
1. Auto
2. Register
3. Static
4. Extern

Auto:
An auto variable is created each time a block ({ and}) is executed and destroyed when the a block terminates. Hence it can not be accessible outside the block.
All variables declared within a block are auto by default.
A function cannot be declared as auto. A formal parameter by default is auto but it can not be explicitly declared.
The default initial value of auto variable is garbage value.

Static:
A static variable is created at the beginning of a program and remains in existence till the end of the program. Hence static variables are initialised once and they retain their values from their previous call.
A variable declared within a function with the keyword static is called function static variable. A variable declared outside a function with a keyword static is called as file static variable. These variables cannot be accessed outside the file.
A formal parameter can not be declared as static.
The default initial value is zero. Therefore static variables need not be initialised to zero unless a different value is to be initialised.


Register:
Registers are special storage areas within the computer’s central processing unit. The actual arithmetic and logical operations that comprise a program are carried out within these registers.
A variable declared as register will be stored on the register of the microprocessor and not on the main memory. Hence a program that uses register variables executes faster than the other similar program without register variable.
A program can contain limited register variables. If more variables are declared as register they will be treated as auto.
The address of a register variable can not be taken through addressof operator(&). A function or a global variable cannot be declared as register.
Large or aggregate data types such as double and arrays cannot be declared as register.
The default initial value of register variable is garbage value.
The syntax as follows:
register int var;

Extern:
When a program spans across different files, a single global variable can be used which is common to all these files with the keyword extern in the declaration except in the file that contains the definition of the variable.
The linker requires that only one of these files have the definition of the identifier.
For a variable declared with the storage class extern memory space will not be allocated but it declares that the memory has been created elsewhere in the program. Hence the initialisation can be done only with the definition.
A formal parameter of a function cannot be declared as extern.
A function can be declared with extern, which indicates that the function is defined in another source file. But it is optional.
extern int fun();
The default initial value of extern variable is zero.



How the processor registers can be used in C ?

By creating register variables. See the answer on Storage classes on how to create register variables.


What is recursion in C?

Recursion is a process in which a construct operates on itself . In C, when a function calls itself, it is called as recursive function. Recursive function reduces a problem into a smaller instance of the same problem.

A recursive definition of f(n) must meet the following requirements:

1. The definition must include the base component in which f(n) is defined directly( non recursively) for one or more values of n. (That the base covers the case n≤k for some constant k).

2. In the recursive component, all occurrences of f have a parameter smaller than n so that repeated application of the recursive component reduces all occurrences of f to the base component.

int fact(int n)
{ 
if(n==0)					//Base Component 
     	return 1;
else
		return n*fact(n-1);			//Recursive Component 
	}


What is structure?

If all the data elements of a program are of the same type, it can be represented as an array. If the elements are of different types such as storing the details of a student, employee, etc., then arrays are inadequate to do the task. Under such circumstances structures are used. Structure is a collection of logically related data items grouped together under a single name, called a structure tag. The data items that make up a structure are called its members or fields and it can be of any type. Since a structure is derived from other data types it is called as user defined data type or derived data type.

struct student
{ 
int roll;
char name[20];
float fees;
};

A structure definition is specified by the keyword struct. This is followed by a template surrounded by braces, which describes the members of the structure.

Here struct is a keyword followed by the name of the structure student. Roll no., name and fees are called as members or fields.


What is union?

A union is declared exactly like a structure, except that the keyword union is used instead of struct. However, the members within a union share the same memory. Hence, all the members of the union variable cannot be initialized at the same time rather only one member can be initialized. The last initialized member occupies the memory location. Therefore only the last initialized member can be accessed.

union sample
{ 
int a;
float b;
};

What is the difference between a structure and a union?


Note: Accessing and manipulating the union variable is same as struct variable.


What is a self-referential structure?

If a structure has pointer to itself as a member then that structure is called as self-referential structure.

struct sample
{
int no;
struct sample *s;
};

Self-Referential structures are very useful in application that involves linked data structures such as lists and trees. The fundamental use of this linked data structure is to avoid allocation of unnecessary memory, during compilation, in storing large database and to allocate it during run-time. In linked list, each component within the structure includes a pointer indicating where the next component can be found. Therefore the relative order of the components can easily be changed, by altering the pointers. In addition, individual components can easily be added or deleted by altering the pointers. As a result, a linked data structure is not confined to some maximum number of components. Rather, the data structure can expand or contract in size as and when required.


Dynamic memory allocation and preprocessors


What is memory leak?

Memory leak occurs whenever memory allocated in the heap is not deallocated i.e whenever there is dynamic memory allocation using malloc, calloc or realloc and the programmer does not free the allocated memory using the free function then there is a memory leak. A memory leak makes the memory unusable for running new or existing programs in the same machine.


What are preprocessor directives?

Preprocessor is a program that modifies the source code before it is passed to the compiler. The modified source code is called as expanded source program. Each of the preprocessor directives begin with a # symbol. It can be placed anywhere in the program but generally it is placed at the beginning of a program.
The features of pre-processors:
1. Macro expansion
2. File Inclusion
3. Conditional Compilation


What functions are used for dynamic memory allocation in C language?

malloc(), calloc(), realloc() and free()


What is the difference between malloc() and calloc()?

Both malloc and calloc are functions in stdlib (in GCC compiler) used for dynamic memory allocation.

void * malloc(size_t size)
The function malloc() allocates a block of size bytes from the free data area( heap) during the runtime. The parameter passed to malloc size_t is like unsigned int but declared in the header file stddef.h. On success, the malloc returns a pointer to the newly allocated block of memory. If memory on the heap is insufficient, then it returns NULL pointer.

Like malloc(), calloc() also allocates memory in the heap during the runtime but unlike malloc(),calloc() takes two parameters.
void *calloc(size_t nitems, size_t size);
The first parameter is the number of blocks to be created and the second parameter is the size of each block. On success it returns a pointer to the newly created block. Due to less memory space if it fails, it returns NULL.

The another difference between calloc() and malloc() is that calloc() initializes all blocks to zero during creation.


How to prevent same header file getting included multiple times?

To prevent the same header file from getting included multiple times in a program, you can use what are called "include guards" or "header guards" in the program.
For example, consider the following header files:

// superheader.h
struct sample{
  int member;
};

// subheader.h
#include "superheader.h"

// And the C file using those headers
// sample.c
#include "superheader.h"
#include "subheader.h"

This will result into duplicate inclusion of the header file superheader.h in the C file sample.c as subheader.h also itself includes superheader.h
One way to avoid this duplicate imports is to use conditional compilation directive #ifndef

// superheader.h
#ifndef SUPERHEADER_H
#define SUPERHEADER_H
struct sample {
    int member;
};
#endif

Now the inclusion of superheader.h will cause the macro SUPERHEADER_H to be defined. So when the header file is included again as a part of subheader.h the macro will not be redefined due to the conditional compilation directive.


What are pragma directives?

The #pragma Directives are used to turn ON or OFF certain features. They vary from compiler to compiler.

Examples of pragmas are:
#pragma startup // you can use this to execute a function at startup of a program
#pragma exit // you can use this to execute a function at exiting of a program
#pragma warn –rvl // used to suppress return value not used warning
#pragma warn –par // used to suppress parameter not used warning


What is the advantage of using macros?

In modular programming, using functions is advisable when a certain code is repeated several times in a program. However, every time a function is called the control gets transferred to that function and then back to the calling function. This consumes a lot of execution time. One way to save this time is by using macros. Macros substitute a function call by the definition of that function. This saves execution time to a great extent.


Miscellaneous


What is a volatile variable?

A volatile variable gives an instruction to the compiler that tells the compiler that it shouldn’t allow any optimizations on the memory allocated for the variable. Generally these optimizations are done beyond the knowledge of the compiler. Certain optimizations may kick in while converting the source code to machine code so that the processor has to perform optimized number of operations.
Example:

int x=0;
for(;x==0;)
{
	// Some processing which does not change x
}

In this case when the compiler compiles the code, it sees that the value x is not used and hence in the machine code it replaces the for loop with a while(1). In this case we might get issues in the future execution of the code when we have stored the address of the variable x in a pointer.


Write a program to print "hello world" without using semicolon?

#include<stdio.h>    
void main(){    
   if(printf("hello world")){}    
}

Write a program to swap two numbers without using third variable?

Assume num1 and num2 are different numbers whose content need to be swapped.

int num1 =2 , num2 =3;
num1+=num2; //num1 now becomes 5
num2=num1-num2;//num2 now becomes 5 - 3 i.e 2
num1=num1-num2; //num1 now becomes 5 - 2 i.e 3

What is the purpose of the keyword typedef?

The typedef keyword allows the user to define a new data type which is equivalent to existing data types. Here the new name is only for name sake whereas in reality it is only a representation of the existing data type.

The general form of defining a new data type is:
typedef existing-type new-type;
Example:
typedef int age;
age person;

Here person is a variable of type age. Since age is a representation of int ,for person variable, two bytes will be allocated.


What is the difference between getch() and getchar() methods?

getchar() is a standard function that gets a character from the stdin.

getch() is non-standard. It gets a character from the keyboard (which may be different from stdin) and does not echo it.


Is the following declaration correct?
char (* ( *f())[])();

Yes. f is a function that returns a pointer to an array of pointers to functions that return a char.


Is the following declaration correct?
void(*f)(int, void(*)());

Yes.f is a pointer to a function which returns nothing and receives as its parameter an integer and a pointer to a function which receives nothing and returns nothing.


What are the advantages of using array of pointers to string instead of an array of strings in C?

While sorting the strings, we need to swap only pointers instead of swapping the whole string which helps in efficient use of memory and time.When we have lot of data,this method should be preferred.


Differentiate between functions getch() and getche().

Both the functions getch() and getche() are used to accept a character input value from the user but there is a difference in their behaviours. When getch() is used, the key that was pressed will not appear on the screen. It is automatically captured and assigned to a variable. When getche() is used, the key that was pressed by the user appears on the screen and is assigned to a variable.


What is the purpose of "register" keyword?

The keyword ‘register’ instructs the compiler to persist the variable that is being declared, in a CPU register.


name