This is Part-B of commonly asked C programming language interview questions along with their answers.
Table of Contents
What is the const pointer in C?
A const
pointer is a pointer that points to a constant value. It can’t modify the value it points to.
int x = 10;
const int *ptr = &x; // ptr is a pointer to a constant integer (can't modify x)
What is the volatile pointer in C?
A volatile pointer is a pointer that points to a volatile variable. It indicates that the value of the variable may change at any time, so the compiler should avoid optimizations related to that variable.
volatile int sensor_value;
volatile int *ptr = &sensor_value; // ptr is a volatile pointer to an integer
Explain the typedef for function pointers in C
typedef can be used to create aliases for function pointer types to simplify their usage.
typedef int (*OperationFunc)(int, int);
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
int main() {
OperationFunc operation;
operation = add;
printf("Addition: %d\n", operation(5, 3));
operation = subtract;
printf("Subtraction: %d\n", operation(5, 3));
return 0;
}
What is the const function in C?
A const function is a function that promises not to modify the state of the object it is called on. The const keyword is used in the function declaration to indicate this promise.
struct Point {
int x;
int y;
};
void printCoordinates(const struct Point *p) {
printf("X: %d, Y: %d\n", p->x, p->y);
}
Explain the extern keyword in C.
extern
is used to declare a global variable or function that is defined in a different source file. It indicates that the variable or function is defined elsewhere
// file1.c
int globalVar = 10;
// file2.c
extern int globalVar; // Declare the variable from file1.c
int main() {
printf("Global variable: %d\n", globalVar); // Access the global variable
return 0;
}
What is a structure in C?
A structure is a user-defined data type that allows you to group different data types together under a single name.
struct Student {
char name[50];
int age;
float gpa;
};
int main() {
struct Student student1;
strcpy(student1.name, "John");
student1.age = 20;
student1.gpa = 3.8;
printf("Name: %s\n", student1.name);
printf("Age: %d\n", student1.age);
printf("GPA: %.2f\n", student1.gpa);
return 0;
}
What are preprocessor directives in C?
Preprocessor directives are instructions to the compiler that start with #
. They are executed before the actual compilation process.
#define PI 3.14159
#define SQUARE(x) ((x) * (x))
int main() {
float radius = 2.5;
float area = PI * SQUARE(radius);
printf("Area of circle: %.2f\n", area);
return 0;
}
These are more C programming language interview questions that cover topics like function pointers, structures, preprocessor directives, and usage of extern
, const
, volatile
keywords. Remember to practice coding and understand the core concepts thoroughly to excel in C programming interviews.