C interview questions for experienced


C interview questions for experienced and explanations
1
Can you write a c program to display mouse?
Answer
Explanation:
Before delving into writing C code to display the mouse pointer, it's imperative to acquire a foundational understanding of essential structures and unions in the C language. The header file dos.h proves pivotal in this regard, defining two crucial structures and one union that form the backbone of mouse input handling and related functionalities.  They are:

1. 
struct BYTEREGS {
unsigned char al, ah, bl, bh;
unsigned char cl, ch, dl, dh;
   };
2. struct WORDREGS {
unsigned int ax, bx, cx, dx;
unsigned int si, di, cflag, flags;
   };
3. union REGS {
struct WORDREGS x;
struct BYTEREGS h;
  };

Note: Try to remember above structures and union.

within the dos.h header file, a particularly significant function is int86(). This function serves as a general interface for software interrupts on the 8086 architecture. It plays a key role in facilitating communication with the hardware and executing specific operations, making it an integral part of tasks related to mouse input handling and other system-level functionalities. It will better to understand it by an example:

C code to display mouse pointer:

#include <dos.h>
#include <stdio.h>
int main(){
union REGS i,o;
i.x.ax=1;
int86(0x33,&i,&o);
return 0;
}

Explanation: To write such program you must have one interrupt table. Following table is only small part of interrupt table:



This table comprises four columns, each serving a distinct purpose:

Input:
This column delineates the input parameters or data required for the specific interrupt service routine (ISR) to execute successfully.

Output:
The output column outlines the results or changes that can be expected after the ISR completes its execution. It encompasses any values or states that may be altered.

Service Number:
The service number column denotes the unique identifier assigned to each interrupt service routine. It serves as a reference to invoke the desired routine through an interrupt call.

Purpose:
The purpose column elucidates the overarching goal or function of the interrupt service routine. It provides a concise description of why the routine is invoked and what task it aims to accomplish.




Now look at the first row of interrupt table. To show the mouse pointer assign ax equal to 1 i.e. service number while ax is define in the WORDREGS

struct WORDREGS {
unsigned int ax, bx, cx, dx;
unsigned int si, di, cflag, flags;
};

And WORDRGS is define in the union REGS

union REGS {
struct WORDREGS x;
struct BYTEREGS h;
};

So to access the structure member ax first declare a variable of REGS i.e.

REGS i, o;

Note: We generally use i for input and o for output

To access the ax write i.x.ax (We are using structure variable i because ax is input (See in the interrupt table)

So to show mouse pointer assign the value of service number to it:

i.x.ax=1;

To provide this information to microprocessor
we use int86 function. It has three parameters

1. Interrupt number i.e. 0x33
2. union REGS *inputregiste i.e. &i
3. union REGS *outputregiste i.e. &o;

So write: int86 (0x33, &i, &o);
Hide
2
Can you write c program which shutdown the window operating system?
Answer
Explanation:
Step 1: Write the following program in TURBO C.

#include <dos.h>
int main (void){
    system("shutdown -s");
return 0;
}

Step 2: Save the above file. Let file name is close.c
Step 3: Only compile the above program.
Step 4: Now close the turbo c compiler and open that directory in window operating system where you have saved the close.c (default directory c:\tc\bin)
Step 5: Double click on its .exe file (close.exe)
After some time your window operating system will shutdown.
Hide
3
Can you explain #pragma warn directive in c by example?
Answer
Explanation:
In c there are many warning messages which can be on or off with help of #pragma warn.
Syntax:

#pragma warn +xxx
#pragma warn –xxx
#pragma warn .xxx

Where
+ means on
- means off
. means on/off (toggle)

xxx is indicate particular warning code in three alphabet. Example: rvl is warning code which means function should return a value.

#include<stdio.h>
#pragma warn –rvl
int main(){
    printf("It will not show any warning message");
    return 0;
}

Output: It will not show any warning message

No warning messages will be displayed during the program execution since the compiler's "return value" (rvl) warning is disabled.


List of warning code:

S.N.
Warning message
Code
ANSI Violations
1
Assigning 'type' to 'enumeration'
eas
2
Bit fields must be signed or unsigned int
bbf
3
Both return and return with a value used
ret
4
Declare type 'type' prior to use in prototype
dpu
5
Division by zero
zdi
6
Hexadecimal value contains more than 3 digits
big
7
Initializing 'enumeration' with 'type'
bei
8
'identifier' is declared as both external and static
ext
9
Ill-formed pragma
ill
10
Initialization is only partially bracketed
pin
11
Redefinition of 'macro' is not identical
dup
12
Suspicious pointer conversion
sus
13
Undefined structure 'structure'
stu
14
Void functions may not return a value
voi
Frequent Errors
1
Code has no effect
eff
2
Function should return a value
rvl
3
Parameter 'parameter' is never used
par
4
Possible use of 'identifier' before definition
def
5
Possibly incorrect assignment
pia
6
Unreachable code
rch
Less Frequent Errors
1
Ambiguous operators need parentheses
amb
2
Array variable 'identifier' is near
ias
3
Call to function with no prototype
pro
4
Call to function 'function' with no prototype
pro
5
Condition is always false
wccc
6
Condition is always true
wccc
7
'identifier' declared but never used
use
8
'identifier' is assigned a value that is never used
aus
9
No declaration for function 'function'
nod
10
Structure passed by value
stv
11
Superfluous & with function
amp
Portability Warnings
1
Constant is long
cln
2
Constant out of range in comparison
rng
3
Conversion may lose significant digits
sig
4
Non portable pointer comparison
cpt
5
Non portable pointer conversion
rpt
6
Mixing pointers to signed and unsigned char
ucp
Hide
4
What is pointer to array in c?
Answer
Explanation:
A pointer that stores the base address of an array or the address of any element within an array is referred to as a pointer to an array.
 For example:

(a)
#include<stdio.h>
int main(){
    int arr[5]={100,200,300};
    int *ptr1=arr;
    char *ptr2=(char *)arr;
    printf("%d   %d",*(ptr1+2),*(ptr2+4));
    return 0;       
}

Output: 300   44

(b)
#include<stdio.h>
int main(){
    static int a=11,b=22,c=33;
    int * arr[5]={&a,&b,&c};
    int const * const *ptr=&arr[1];
    --ptr;
    printf("%d ",**ptr);
    return 0;        
}

Output: 11
Hide
5
Can you declare such function which return type is pointer to a pointer?
Answer
Explanation:
#include<stdio.h>
int** ibm(){
    static int a[]={4,8,12,16};
    static int *pointer=a;
    static int **p=&pointer;
    return p;
}
int main(){
    int **ptr;
    ptr=ibm();
    printf("%d",++**ptr);
    return 0;        
}

Output: 5
Hide
6
Is it possible to rename any function in c?
Answer
Explanation:
The typedef keyword can be employed to provide an alternative name for functions, particularly when the original function declaration is intricate. This proves beneficial for enhancing code readability, especially in scenarios where numerous functions of the same type need concise and simpler names.

typedef void govinda(int);
int main(){
    govinda one,two;
    one(1);
    two(2);
    return 0;        
}
void one(int x){
    printf("FROM ONE %d",x);
}
void two(int y){
    printf("\nFROM TWO %d",y);
}

Output:
FROM ONE 1
FROM TWO 2
Hide
7
Can you explain pointer to union in c by a good example?
Answer
Explanation:
A "pointer to structure" refers to a pointer that is directed towards a structure in C. This type of pointer holds the memory address of a structure variable, enabling indirect access to its members and facilitating manipulation of the contained data. Examples of pointers to union:
What will be output if you will execute following code?

#include<stdio.h>
union address{
char *name;
char street[10];
int pin;
};
int main(){
union address emp,*p;
emp.name="ja\0pan";
p=&emp;
printf("%s %s",p->name,(*p).name);
return 0;
}
Output: ja ja
Explanation:
The pointer 'p' is designated as a pointer to a union address. The operators '->' and '(*).' are functionally equivalent, serving to access data members of the union through the union's pointer. Additionally, the '%s' format specifier is employed to print strings up to the null character, denoted by '\0'.
Hide
8
Can you declare pointer to three dimensional arrays in c?
Answer
Explanation:
Examples of pointers to 3 dimensional array:

#include<stdio.h>
int main(){
const array[2][3][3]={0,1,2,3,4,5,6,7,8,9,10,11,12};
int const (*ptr)[2][3][3]=&array;
printf("%d ",*(*(*ptr)[1]+2));
return 0;
}
Output: 11
Explanation:
The array [2][3][3] is a three-dimensional array containing constant integers as its elements.

The pointer 'ptr' is designated as a pointer to a three-dimensional array containing constant integers.  Pictorial representation:
Note: In the above figure upper part of box represent content and lower part represent memory address. We have assumed arbitrary address.
*(*(*ptr) [1] +2)
=*(*(*&array) [1] +2)
=*(*array [1] +2)
=*(array [1] [0] +2)
=array [1] [0] [2] 
I.e. array element at the 1*(3*3) +0(3) + 2=11th position starting from zero which is 11.
Hide
9
Can you write a c program to draw a line using graphics video memory in c using far pointer?
Answer
Explanation:
Segment number 0xA is identified as graphics video memory, encompassing 720 columns and 400 rows. The point where rows and columns intersect defines a pixel, and each pixel occupies one byte, storing color information.  Examples:

(q)What will be output of following c program?
#include <dos.h>
#include<stdio.h>
int main(){
int j;
union REGS i,o;
char far *ptr=(char *)0XA0000000;
i.h.ah=0;
i.h.al=0x13;
int86(0x10,&i,&o);
for(j=1;j<=100;j++){
*(ptr+j)=4;
}
return 0;
}
Output: One red color line in the graphics console as shown in the following figure:



In the above program what is following codes?
union REGS i,o;
i.h.ah=0;
i.h.al=0x13;
int86(0x10,&i,&o);
Answer: 
The purpose of this code is to transition the graphics console window to a 256-bit color mode from the default console window of the Turbo C++ IDE.
Copy the following code and execute the code in Turbo c compile and see what is displaying.
(1)What will be output of following c program?
#include <dos.h>
#include<stdio.h>
int main(){
int j,k;
union REGS i,o;
char far *ptr=(char *)0XA0000000;
i.h.ah=0;
i.h.al=0x13;
int86(0x10,&i,&o);
for(k=0;k<100;k++){
for(j=1;j<=319;j++){
*(ptr+j+k*320)=k;
}
}
return 0;
}
(2)What will be output of following c program?
#include <dos.h>
#include<stdio.h>
int main(){
int j,k;
union REGS i,o;
char far *ptr=(char *)0XA0000000;
i.h.ah=0;
i.h.al=0x13;
int86(0x10,&i,&o);
for(k=0;k<100;k++){
for(j=1;j<=319;j++){
*(ptr+j+k*320)=k;
}
}
return 0;
}
Hide
10
Can you give me any example of pointer to array of structure in c?
Answer
Explanation:
A pointer to an array whose elements are pointers to structures is referred to as a "pointer to an array of structures."
What will be output if you will execute following code?

#include<stdio.h>
struct emp{
char *name;
int id;
};
int main(){
static struct emp e1={"A",1},e2={"B",2},e3={"C",3};
struct emp(*array[])={&e1,&e2,&e3};
struct emp(*(*ptr)[3])=&array;
printf("%s %d",(**(*ptr+1)).name,(*(*ptr+1))->id);
return 0;
}
Output: B 2
Explanation:
(**(*ptr+1)).name
=(**(*&array+1)).name //ptr=&array
=(**(array+1)).name //from rule *&p =p
=(*array[1]).name //from rule *(p+i)=p[i]
=(*&e2).name //array[1]=&e2
=e2.name=”B” //from rule *&p =p
(*(*ptr+1))->id
=(**(*ptr+1)).id //from rule -> = (*).
=e2.id=2
Hide
11
Do you know, what is the meaning and use of static keyword in c?
Answer
Explanation:
The static keyword in C is employed to declare static variables, and this modifier is applicable to various data types, including int, float, double, arrays, pointers, structures, functions, and others.

Important points about static keyword:

1.It is not the default storage class for global variables. For example, analyze the following three programs and its output.

(a)
#include<stdio.h>
int a;
int main(){
    printf("%d",a);
    return 0;
}

Output: 0

(b)
#include<stdio.h>
static int a;
int main(){
    printf("%d",a);
    return 0;
}

Output: 0

(c)
#include<stdio.h>
extern int a;
int main(){
    printf("%d",a);
    return 0;
}

Output: Compilation error

Upon initial inspection of the output from the three aforementioned codes, it might seem that the default storage class for global variables is static. However, this assumption is inaccurate. The reason lies in understanding the extern storage class.

2. The default initial value of static integral type variables in C is zero. If the integral type variable is a pointer, the default initial value is typically NULL.  For example:

#include <stdio.h>
static char c;
static int i;
static float f;
static char *str;  
int main(){
    printf("%d %d %f %s",c,i,f,str);
    return 0;
}

Output: 0 0 0.000000 (null)

3.A static variable can be declared multiple times, but initialization is permissible only once for the same variable. For example:

(a)
#include <stdio.h>
static int i;        //Declaring the variable i.
static int i=25;     //Initializing the variable.
static int i;        //Again declaring the variable i.
int main(){
    static int i;    //Again declaring the variable i.
    printf("%d",i);
    return 0;
}

Output: 25

(b)
#include <stdio.h>
static int i;        //Declaring the variable
static int i=25;     //Initializing the variable
int main(){
    printf("%d",i);
    return 0;
}
static int i=20;     //Again initializing the variable

Output: Compilation error: Multiple initialization variable i.

4. In C, assignment statements, like other executable code, cannot be placed at the global scope. Assignment statements need to be inside a function or a code block. Global scope is generally reserved for variable declarations and function prototypes. For example:

#include <stdio.h>
static int i=10;   //Initialization statement
i=25;              //Assignment statement
int main(){
    printf("%d",i);
    return 0;
}
            
Output: Compilation error

Note: Assigning a value to a variable at the time of its declaration is termed "initialization." On the other hand, assigning a value to a variable at a later point, separate from its declaration, is referred to simply as an "assignment."

(b)
#include <stdio.h>
static int i=10;
int main(){
    i=25;       //Assignment statement
    printf("%d",i);
    return 0;
}

Output: 25

(5) A static variable is initialized only once throughout the entire program's execution. This initialization occurs during the startup phase, and the variable retains its value across subsequent calls to the function or block where it is declared.  For example:

#include <stdio.h>
static int i=10;
int main(){
    i=5;
    for(i=0;i<5;i++){
         static int a=10; //This statement will execute
                          //only time.
         printf("%d",a++);//This statement will execute
                          //five times.
    }  
    return 0;
}

Output: 10 11 12 13 14

(6)When a static variable is declared locally within a block, its visibility is confined to the specific block where it is declared.

 For example:

#include<stdio.h>
int main(){
    {                       
         static int a=5;     
         printf("%d",a);
    }                       
    //printf("%d",a);   variable a is not visible here.
    return 0;   
}

Output: 5

7. When a static variable or function is declared globally, its visibility is restricted to the file in which it has been declared and is not accessible from other files.  For example:

(a)
#include<stdio.h>
static float a=144.0f; //global to all function
int main(){
    {                        
         printf("%d",a); //variable a is visible here.
       //printf("%d",b); variable b is not visible here.
    }                       
    printf("%d",a);   //variable a is visible here.
    //printf("%d",b);    variable b is not visible here.
    return 0;
}
static int b=5;    //Global to only calculation function
void calculation(){
    printf("%d",a);   //variable a is visible here.
    printf("%d",b);   //variable b is visible here.
}
   
(b) Consider a c program which has written in two files named as one.c and two.c:

//one.c
#include<conio.h>
static int i=25;
static int j=5; 

int main(){
    sum();
    return 0;
}

//two.c
#include<stdio.h>
extern int i; //Declaration of variable i.
extern int j; //Declaration of variable j.
/**
Above two lines will search the initialization statement of variable i and j either in two.c (if initialized variable is static or extern) or one.c (if initialized variable is extern) 
*/
extern void sum(){
    int s;
    s=i+j;
    printf("%d",s);
}

Compile and execute above two file one.c and two.c at the same time:

In Turbo c compiler

Step 1: Write above two codes in the file named as one.c and two.c (You can give any name as you like) and save it.

Step 2: In Turbo c++ IDE click on Project -> Open project menu as shown in following screen dump:



Step 3: After Clicking on open project you will get following screen:



In Open project File text field write any project name with .prj extension. In this example I am writing project name as CProject.PRJ. Now press OK button.

Step 4: After pressing OK button you will get following screen:


Now click on Project -> Add item menu.

Step 5: After clicking Add item you will get following screen:



Enter the names of each C source code file sequentially into the name text field. Begin by typing "one.c" and proceed by clicking the "Add" button. Subsequently, input "two.c" and repeat the process for each file in succession.


Step 6: After inputting all the C source code file names and clicking on the "Done" button, the system will conclude the input process.

you will get following screen:


Towards the bottom of the window, you will find information such as the project name and a list of the files you have added.

Step7: Compile the two files by pressing Alt+F9, and execute the program by pressing Ctrl+F9.

Note: To close the project, navigate to Project -> Close Project.



Output: Compilation error: Undeclared symbols 'i' and 'j'.

The variables 'i' and 'j,' initialized in two.c, are not visible in file one.c. This example underscores that the visibility of globally declared static variables is limited to the file in which they are declared.

Note: In the above example, the function 'sum,' which was declared and defined in two.c, also has the storage class 'extern.' This allows us to call it from another file (one.c). If it were static, calling the function 'sum' would not be possible, as the static storage class confines visibility to the file where it is declared.

(8)If we static variable has declared locally or globally its scope will always whole the program. For example:

(a) //locally declaration of static variable
#include<stdio.h>
void visit();
int main(){
    int i=0;
    {                    //Opening inner block
         static int a=5;  //locally declaration
         XYZ:;            //Label of goto statement
         printf("%d  ",a);
         a++;
         i++;
    }                     //closing inner block.   
    visit();
    /* printf("%d",a); Variable a is not visible here but
    it is alive. */
    if(i<5)
             goto XYZ;
    return 0;
}
void visit(){ 
}

Output: 5 6 7 8 9

Explanation: When the program control exits the inner block where variable 'a' is declared, the variable 'a' is not visible outside of that block, but its scope persists throughout the program. If, using a goto statement, control returns to the inner block, it prints the previously incremented values. This behavior is achievable with static variables, unlike auto or register variables, which lose their values when exiting their scope.

(b)
//Locally declarations of variable   

There are two c source code files:
//one.c
#include<stdio.h>
#include<conio.h>
void main(){
    int i;
    for(i=0;i<3;i++){
         {
             static int a=5;
             printf("%d\n",a);
             a++;
         }
         visit();
    }
    getch();
}

//two.c
#include<stdio.h>
void visit(){
    printf("Don’t disturb, I am learning storage class");
    /* printf("%d",a); Variable a is not visible here but
    It is alive. */
}

Now compile and execute both files together:
Output:
5
disturb, I am learning storage class
6
disturb, I am learning storage class
7
disturb, I am learning storage class

Explanation: When control goes to another file and comes even that variable didn’t dead and it prints previous incremented value.

Note: In both examples if you will declare static variable globally you will get same output.

9. A static variables or functions have internal linkage. An internal linkage variables or functions are visible to the file where it has declared.  
Hide
12
How singed int is stored in the memory?
Answer
Explanation:
Total size of unsigned int: 16 bit
Those eight bits are use as:
Data bit: 15
Signe bit: 1

Note: In c negative number is stored in 2’s complement format. Example:

(1)Memory representation of:

signed int a=7;            (In Turbo c compiler)
signed short int a=7 (Both turbo c and Linux gcc compiler)
Binary equivalent of data 7 in 16 bit:  00000000 00000111
Data bit: 0000000 00000111 (Take first 15 bit form right side)
Sign bit: 0  (Take leftmost one bit)

First eight bit of data bit from right side i.e. 00000111 will store in the leftmost byte from right to left side and rest seven bit of data bit i.e. 0000000 will store in rightmost byte from right to left side as shown in the following figure:   



(2)Memory representation of:

signed int a=-7;  (In Turbo c compiler)
signed short int a=-7 (Both turbo c and Linux gcc compiler)
Binary equivalent of data 7 in 16 bit:  00000000 00000111
Binary equivalent of data -7 will be its 2’s complement:
1’s complements of 00000000 00000111 is 11111111 11111000
2’s complement will be:


Binary equivalent of data -7 in 16 bit: 11111111 11111001
Data bit: 1111111 11111001 (Take first 15 bit form right side)
Sign bit: 1    (Take leftmost one bit)
First eight bit of data bit from right side i.e. 00000111 will store in the leftmost byte from right to left side and rest seven bit of data bit i.e. 1111111 will store in rightmost byte from right to left side as shown in the following figure:   
Hide
13
What is offset address of pointers in c?
Answer
Explanation:

Each segment is divided into two parts:

  1. 1. Segment Number (4 bits): Identifies the segment, providing a unique identifier within the system.
  2. 2. Offset Address (16 bits): Specifies the offset within the segment, determining the location of the specific data or instruction within that segment.


So, in the other words we can say memory address of any variable in c has two parts segment number and offset address.

In the Turbo C 3.0 environment, where the segment number is 4 bits and the offset address is 16 bits, you are correct in your analysis of a physical address like 0x500F1.

Breaking down the physical address 0x500F1:

Segment Number: The leftmost hexadecimal digit (5) indicates the segment number.
Offset Address: The remaining four hexadecimal digits (00F1) represent the offset address.
So, for the given physical address 0x500F1, the segment number is 5, and the offset address is 00F1.






Write a program to find the offset address of any variable?

#include<stdio.h>
int main(){
int x;
printf("%u ",&x); //To print offset address
printf("%p ",x); //To print segment address
printf("%p ",&x); //To print offset address
printf("%fp ",&x); //To print segment address : offset address
return 0;
}
Hide
14
What is difference between .com program and .exe program?
Answer
Explanation:
Both .com and .exe programs are executable, but .com programs typically execute faster than .exe programs. Drivers are commonly .com programs. Additionally, .com files are given higher preference than .exe files. For example:

 To open the Command Prompt in a Windows OS:

Press Win + R to open the Run dialog.
Type cmd and press Enter.
To open Notepad from the Command Prompt:

Type notepad in the Command Prompt.
Press Enter.
Executing the command notepad launches the Notepad application (notepad.exe).




Repeat the same task but now first create any .com file in the same working directory. We can create it as open the notepad save it as notepad.com, set save as type is All files or we can create the .com file from command prompt.Then type notepad in command prompt and press the enter key you will get error message like:   
C:\notepad.com is not a valid Win32 application.


This observation affirms the higher precedence of .com over .exe programs. A .com file, a binary executable utilized in MS-DOS, exclusively contains code and data. It consolidates code and data within a single segment. In Turbo C, the memory model should be set to tiny for creating a .com program. We will delve into the process of creating a .com file in Turbo C later.


Hide
15
Can you write any c program which print "Hello" ten times without using any conditional operators?
Answer
Explanation:
#include <stdio.h>
int main(int argc, char *argv[]){
    int i=0;
    while(10 - i++)
         printf("Hello");
    return 0;
}

Or
#include <stdio.h>
int main(int argc, char *argv[]){
    int i;
    for(i=0;10 - i;i++)
    printf("Hello");
    return 0;
}
Hide

8 comments:

Anonymous said...

good for practice,thanks for posting

Anonymous said...

its goog

Anonymous said...

Really good one

Unknown said...

Good collection..

Saurabh said...

In question 11, example 3(a) ans should be 0.

Unknown said...

Good question thank you

Unknown said...

Very good.

Unknown said...

very good describe about negative integers